[英]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.