[英]Cannot properly create rollover on dynamically created html element
我基於循環名稱數組動態創建了一些按鈕,然后想在這些按鈕上添加翻轉動作,但是此代碼中的alert()
始終打印最后一項的名稱( 黑色 )。
我嘗試在該alert()
部分使用eval()
,但是沒有任何區別。 我希望它返回紅色,綠色或黑色,具體取決於我將鼠標懸停在哪個按鈕上。
<div id="channels_buttons_container">
</div>
<script>
channels_array = ["red", "green", "black"];
for(var i = 0; i < channels_array.length; i++) {
loop_channel_name = channels_array[i];
// append an element inside the container
var new_button_element = document.createElement("span");
new_button_element.id = 'channel_button_'+loop_channel_name;
new_button_element.innerHTML = '<br>BLA BLA';
document.getElementById('channels_buttons_container').appendChild(new_button_element);
// try to add rollover actions on the new button
document.getElementById('channel_button_'+loop_channel_name).onmouseover = function(){
alert('Rollover '+loop_channel_name);
}
}
</script>
loop_channel_name
初始化為全局變量,因為您沒有使用var
關鍵字。 嘗試使用var loop_channel_name
而不是loop_channel_name
。 在for循環的第一次迭代中初始化loop_channel_name
時,您將其創建為全局變量,而在后續迭代中,則僅對其進行更新而不是創建新引用。 通過在警報中引用loop_channel_name
,您將引用全局變量,該變量在循環的最后一次迭代中已更新為black
,因此它始終會警報black
。
例
<div id="channels_buttons_container">
</div>
<script>
channels_array = ["red", "green", "black"];
for(var i = 0; i < channels_array.length; i++) {
var loop_channel_name = channels_array[i];
var new_button_element = document.createElement("span");
new_button_element.id = 'channel_button_'+loop_channel_name;
new_button_element.innerHTML = '<br>BLA BLA';
document.getElementById('channels_buttons_container').appendChild(new_button_element);
document.getElementById('channel_button_'+loop_channel_name).onmouseover = function(){
alert('Rollover '+loop_channel_name);
/*You could also do*/
alert('Rollover '+ channels_array[i]);
}
//
}
</script>
代碼沒關系,但是當您使用“ loop_channel_name”時,使用數組的最后一個元素。 您必須傳遞實際元素(this):
document.getElementById('channel_button_'+loop_channel_name).onmouseover = function(){
alert('Rollover '+this.id);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.