JavaScript Onclick, 익명 기능
-
21-08-2019 - |
문제
저는 시작 JavaScript 프로그래머입니다. 나는 Lightbox 2와 비슷한 것을 만들려고하지만 훨씬 간단합니다. 내가 스스로 처음부터하고 싶은 유일한 이유는 내가 배울 수 있기 때문입니다. 그러나 이미지가 표시되는 마지막 중요한 부분에 붙어 있습니다. 나는이 문제가 익명의 기능에 대한 과제와 함께 Onclick을 사용하려고하는 곳이라고 생각합니다.elem [i] .onclick = function () {liteboxfocus (imgsource, imgtitle); 거짓을 반환;};. 내 코드를 실행하고 Google 로고를 클릭하면 Google의 로고 및 제목 대신 Yahoo 로고와 제목이 나타납니다. 그러나 Yahoo 로고를 클릭하면 정상적으로 작동하므로 익명 기능이 마지막 루프에만 유지되는 것 같습니다. 미리 감사드립니다 !!!
편의를 위해 전체 CSS/JS/XHTML을 한 페이지에 배치했습니다.
<html> <head> <title>Erik's Script</title> <style type="text/css"> #liteBoxBg, #liteBox { display: none; } #liteBoxBg { background-color: #000000; height: 100%; width:100%; margin:0px; position: fixed; left:0px; top: 0px; filter:alpha(opacity=80); -moz-opacity:0.8; -khtml-opacity: 0.8; opacity: 0.8; z-index: 40; } #liteBox { background-color:#fff; padding: 10px; position:absolute; top:10%; border: 1px solid #ccc; width:auto; text-align:center; z-index: 50; } </style> <script type="text/javascript"> window.onload = start; function start(){ var imgTitle = "No title"; var imgSource; var elem = document.getElementsByTagName("a"); var i; //Dynamically insert the DIV's to produce effect var newDiv = document.createElement('div'); newDiv.setAttribute("id", "liteBox"); document.getElementsByTagName("body")[0].appendChild(newDiv); newDiv = document.createElement('div'); newDiv.setAttribute("id", "liteBoxBg"); document.getElementsByTagName("body")[0].appendChild(newDiv); //Check those anchors with rel=litebox for(i = 0;i < elem.length;i++){ if(elem[i].rel == "litebox"){ imgSource = elem[i].href.toString(); imgTitle = elem[i].title; elem[i].childNodes[0].style.border="0px solid #fff"; elem[i].onclick = function (){liteBoxFocus(imgSource,imgTitle); return false;}; } } //When foreground is clicked, close lite box document.getElementById("liteBoxBg").onclick = liteBoxClose; } //Brings up the image with focus function liteBoxFocus(source,title){ document.getElementById("liteBox").style.display = "block"; document.getElementById("liteBox").innerHTML = "<h1>" + title + "</h1>" + "<img src='" + source + "'/><br />" + "<a href='#' onclick='liteBoxClose();'><img src='images/litebox_close.gif' border='0' alt='close'/></a>"; document.getElementById("liteBoxBg").style.display = "block"; } //closes lite box function liteBoxClose(){ document.getElementById("liteBox").style.display = "none"; document.getElementById("liteBoxBg").style.display = "none"; return false; } </script> </head> <body> <a href="http://www.google.com/intl/en_ALL/images/logo.gif" rel="litebox" title="Google Logo"><img src="http://www.google.com/intl/en_ALL/images/logo.gif" alt="" /></a> <a href=" http://www.barbariangroup.com/assets/users/bruce/images/0000/4121/yahoo_logo.jpg" rel="litebox" title="Yahooo Logo"><img src=" http://www.barbariangroup.com/assets/users/bruce/images/0000/4121/yahoo_logo.jpg" alt="" /></a> </body> </html>
해결책
이벤트 핸들러는 둘러싸는 범위의 변수에 대한 "라이브"포인터를 기억하는 클로저를 형성합니다. 그래서 실제로 실행되면 마지막 가치가 있습니다. imgSource
그리고 imgTitle
가졌다.
대신,이 패턴을 사용하여 변수 값을 로컬라이션 할 수 있습니다. 이렇게하면 호출 될 때마다 GetClickHandler 내부에서 소스 및 제목 사본이 생성됩니다. 반환 된 함수는 루프 반복에서 값을 기억합니다.
//Check those anchors with rel=litebox
for(i = 0;i < elem.length;i++){
if(elem[i].rel == "litebox"){
imgSource = elem[i].href.toString();
imgTitle = elem[i].title;
elem[i].childNodes[0].style.border="0px solid #fff";
elem[i].onclick = getClickHandler(imgSource, imgTitle);
}
}
//Brings up the image with focus
function getClickHandler(source,title){
return function() {
document.getElementById("liteBox").style.display = "block";
document.getElementById("liteBox").innerHTML = "<h1>" + title + "</h1>" +
"<img src='" + source + "'/><br />" +
"<a href='#' onclick='liteBoxClose();'><img src='images/litebox_close.gif' border='0' alt='close'/></a>";
document.getElementById("liteBoxBg").style.display = "block";
}
}
제휴하지 않습니다 StackOverflow