簡體   English   中英

使用 JavaScript 的 onclick 屬性中的變量范圍

[英]Variable scope in onclick attribute with JavaScript

我正在使用Prototype並嘗試在循環中動態訪問變量。

代碼比我說得好:

for (var i=0;i<5;i++) {
  $('parent' + i).insert(
    '<input type="button" value="Cancel" onclick="$('parent' + i).remove()" />',
    {position: 'after'}
  );
}

問題是當我點擊任何Cancel按鈕時, i is not defined

如何改變變量的范圍,使i保持每個按鈕正確的價值?

我對任何變通辦法都不感興趣。

你可以這樣做 -

for (var i = 0; i < 5; i++) {

    $('parent' + i).insert('<input type="button" value="Cancel" onclick="$(\'parent' + i + '\').remove()" />', {position: 'after'});
}

它會像這樣呈現 -

<input type="button" value="Cancel" onclick="$('parent1').remove()" />
<input type="button" value="Cancel" onclick="$('parent2').remove()" />
<input type="button" value="Cancel" onclick="$('parent3').remove()" />
...

等等。

我認為您將i放入帶引號的字符串而不是parent因此它處於錯誤的范圍級別(從概念上講)。

for (var i=0;i<5;i++)
{
    $('parent' + i).insert(
      '<input type="button" value="Cancel" onclick="$(\'parent' + i +
         '\').remove()" />', {position: 'after'});
}

你不需要 i 變量。 如果要刪除該輸入的父級,請執行以下操作:

<input type="button" value="Cancel" onclick="this.parentNode.parentNode.removeChild(this.parentNode)" />

或者如果你真的想要,你可以:

for (var i=0;i<5;i++) {
    $('parent' + i).insert('<input type="button" value="Cancel" onclick="$(\'parent' + i + '\').remove()" />', {position: 'after'});
}

暫無
暫無

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

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