不能将空值赋给jquery中的变量

时间:2015-01-22 15:59:01

标签: javascript jquery html css html5

这里一旦我在slideUp中为'img'变量指定了一个null值,并且调用'click on imageGallery'img值是'undefined',为什么会这样?

$(".imageGallery").click(function(){
    console.log(img+"first");
    var img = $(this).attr("src"); //image source
    console.log(img+"second");
    var num = $(this).attr("alt"); //image name
    $('#popup').slideDown("600",function(){
        $(this).html("<div> <p>"+num+"</p> </div> <img src="+img+">");
        $("#popup p").addClass("popupName");            
        $("#popup img").addClass("popupImg");
        $("#popup div").addClass("popupNameBg");
    })
    $('#popup').click(function(){           
        $('#popup').slideUp("500");
        img = null;
        console.log(img+"third");
        return false;
    })      
})

1 个答案:

答案 0 :(得分:3)

在设置之前,请先阅读img。当然,这将是未定义的,因为这是hoisted variables work的方式。

console.log(img+"first");  <--- reading variable before you set the value, it will be undefined
var img = $(this).attr("src"); <-- /set variable value
console.log(img+"second");  <-- will have new value

您的代码实际上就是这样:

var img;
console.log(img+"first");  
img = $(this).attr("src");
console.log(img+"second");

将其设置为null意味着没有任何内容,因为每次单击您都处于新的“范围”并定义新变量。因此,当您单击弹出窗口时,它将img设置为null,问题是您不再使用该变量。

同样在每次点击时,您都会将新点击绑定到弹出窗口,这意味着您将有很多点击事件。

相关问题