簡體   English   中英

范圍錯誤的變量(可能需要關閉嗎?)

[英]Variable in wrong scope (maybe needs a closure?)

我有以下代碼需要關閉:

var numItems = document.getElementsByClassName('l').length;
for (var i = 0; i < numItems; i++) {
  document.getElementsByClassName('l')[i].onclick = function (e){
    preview(this.href, i);
  };
}

發生的情況是,每當單擊一個項目時,預覽總是與i相同

我懷疑我需要做的是

function indexClosure(i) {
  return function(e) {
    preview(this.href, i);
  }
}

並分配onclick像這樣:

document.getElementsByClassName('l')[i].onclick = indexClosure(i);

但后來this將不再是指我的鏈接......這是怎么解決問題?

使用閉包捕獲周期計數器:

var numItems = document.getElementsByClassName('l').length;
for (var i = 0; i < numItems; i++) {
  (function(i){
    document.getElementsByClassName('l')[i].onclick = function (e){
      preview(this.href, i);
    };
  }(i))
}

不會的onclick通(sender, eventArgs)允許您訪問this通過sender

暫無
暫無

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

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