簡體   English   中英

無法在點擊事件中使用變量?

[英]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();
});

一切正常,但是自然地,即使我例如單擊#toggleCommentForm2,也只能#writeComments1 slideToggles。

我的問題是,為什么不能在點擊事件中使用變量“ 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對象進行操作更復雜的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM