javascript onclick,匿名函数 [英] javascript onclick, anonymous function

查看:162
本文介绍了javascript onclick,匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名JavaScript程序员。我正在尝试创建类似于Lightbox 2的内容,但要简单得多。为什么我想从头开始做我自己的唯一原因是我可以学习。不过,我一直被困在显示图像的最后关键部分。我相信问题出在我尝试使用onclick并赋值给一个匿名函数: elem [i] .onclick = function(){liteBoxFocus(imgSource,imgTitle);返回false;};
。如果您运行我的代码并尝试点击Google徽标,它会显示yahoo徽标和标题,而不是谷歌的徽标和标题。但是,当你点击雅虎标志时,它可以正常工作,所以似乎匿名函数只适用于最后一个循环。在此先感谢!!!

为了您的方便,我已将整个CSS / JS / XHTML放在一个页面中。

 
< html>
< head>
< title> Erik's Script< / title>

< style type =" text / css">
#liteBoxBg,#liteBox {
display:none;
}

#liteBoxBg {
background-color:#000000;
身高:100%;
宽度:100%;
margin:0px;
位置:固定;
left:0px;
top:0px;
filter:alpha(opacity = 80);
-moz-opacity:0.8;
-khtml-opacity:0.8;
不透明度:0.8;
z-index:40;
}

#liteBox {
background-color:#fff;
padding:10px;
位置:绝对;
top:10%;
border:1px solid #ccc;
width:auto;
text-align:center;
z-index:50;
}
< / style>

< script type =" text / javascript">

window.onload = start;

函数start(){

var imgTitle ="无标题" ;;
var imgSource;
var elem = document.getElementsByTagName(" a");
var i;

//动态插入DIV以产生效果
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);

//用rel = litebox
检查锚点(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);返回false;};
}
}

//单击前景时,关闭精简盒
document.getElementById(liteBoxBg)。onclick = liteBoxClose;
}

//带有焦点的图像
function liteBoxFocus(source,title){
document.getElementById(" liteBox")。s​​tyle.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;
}

//关闭文本框
函数liteBoxClose(){
document.getElementById(" liteBox")。s​​tyle.display =" none";
document.getElementById(" liteBoxBg")。s​​tyle.display =" none";
返回false;
}

< / script>



< / head>

< body>

< a href =" http://www.google.com/intl/zh_CN/ALL/images/logo.gif"的rel =" litebox" title =" Google徽标">< img src =" http://www.google.com/intl/zh_CN/ALL/images/logo.gif" ALT ="" />< / A>

< a href ="
http://www.barbariangroup.com/assets/users/bruce/images/0000/4121/yahoo_logo.jpg"的rel =" litebox" title =Yahoo! Logo>< img src ="
http://www.barbariangroup.com/assets/users/bruce/images/0000/4121/yahoo_logo.jpg" ALT ="" />< / A>



< / body>
< / html>


解决方案

你的事件处理器形成一个闭包,记住一个活附上范围。所以当它们被实际执行时,它们的最后一个值是 imgSource imgTitle 有。



相反,您可以使用此模式来定位变量值。这将在每次调用getClickHandler时创建源和标题副本。返回的函数因此会记住该循环中的值。

  //使用rel = litebox $ b $检查锚点b为(i = 0; 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);



$ b //带有焦点的图像
函数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;
}
}


I am a beginning javascript programmer. I am trying to create something similar to Lightbox 2, but much simpler. The only reason why I want to do it from scratch on my own is so that I can learn. However, I've been stuck on the last critical part where it displays the image. I believe the problem lies where I try to use onclick with assignment to an anonymous function:elem[i].onclick = function (){liteBoxFocus(imgSource,imgTitle); return false;}; . If you run my code and try clicking on the google logo it'll bring up the yahoo logo and title instead of google's logo and title. However when you click on the yahoo logo it works fine so it seems that the anonymous function only holds for the last loop. Thanks in advance!!!

I have placed the entire CSS/JS/XHTML in one page for your convenience.

<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>

解决方案

Your event handlers form a closure that remember a "live" pointer to the variables in the enclosing scope. So when they are actually executed, they have the last value imgSource and imgTitle had.

Instead, you can use this pattern to localize the variable values. This will create copies of source and title inside getClickHandler each time it is called. The returned function hence remembers the values in that iteration of the loop.

//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";
    }
}

这篇关于javascript onclick,匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆