不能在点击事件中使用变量?

Can't use variable inside of click event?

我有这个代码,它是 javaScript 和 jQuery:

for (thisLooper = 1; thisLooper < 4; thisLooper++) {

    if ($("#writeComments"+thisLooper).length > 0) {
        $("#writeComments"+thisLooper+",#comments"+thisLooper+", #infoSpan"+thisLooper+"").hide();
        $("#toggleCommentForm"+thisLooper).click(function () {
            $("#writeComments+thisLooper").slideToggle();
        });
    }

}

它的作用:

  1. 检查 #writeComments1 是否存在
  2. 如果存在,隐藏#writeComments1、#comments1 和#infoSpan1
  3. 然后,如果有人点击#toggleCommentForm1,slideToggle #writeComments1
  4. 为#writeComments2 和它的朋友做这一切
  5. 为#writeComments3 和它的朋友做这一切

上面的代码没有任何反应,但如果我替换:

$("#toggleCommentForm"+thisLooper).click(function () {
    $("#writeComments+thisLooper").slideToggle();
});

这个宽度:

$("#toggleCommentForm"+thisLooper).click(function () {
    $("#writeComments1").slideToggle();
});

一切正常,但自然只有 #writeComments1 slideToggles,即使我点击 #toggleCommentForm2 也是如此。

我的问题是,为什么我不能在点击事件中使用变量 "thisLooper"?

循环中的闭包将解决眼前的问题(当然会将变量放在字符串之外),以便在 click 回调函数中保留索引值。

for (index = 1; index < 4; index++) {
    (function(thisLooper){
        if ($("#writeComments"+thisLooper).length > 0) {
            $("#writeComments"+thisLooper+",#comments"+thisLooper+", #infoSpan"+thisLooper+"").hide();
            $("#toggleCommentForm"+thisLooper).click(function () {
                $("#writeComments"+thisLooper).slideToggle();
            });
        }
    })(index);

}

您还应该创建一个本地 var 而不是继续重新查询选择,但我需要先查看您的完整 HTML(因为代码有点奇怪)

问题是你的循环变量没有正确关闭;除了使用闭包来解决该问题(这是 TrueBlueAussie 在他的回答中解释的),您还可以考虑将点击处理程序绑定到您希望在其上执行幻灯片的元素:

$("#toggleCommentForm"+thisLooper).click($.proxy(function () {
     // this is a jQuery object
     this.slideToggle();
}, $("#writeComments"+thisLooper));

不过请注意,闭包可以更好地解决比仅对单个 jQuery 对象进行操作更复杂的问题。