我基于循环遍历名称数组动态创建了一些按钮,然后我想在这些按钮上添加翻转操作,但此代码中的alert()
始终打印 last的名称 item(黑色)。
我尝试在eval()
部分使用alert()
,但它没有任何区别。
我希望它能够返回红色,绿色或黑色,具体取决于我将鼠标悬停在哪个按钮上。
<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>
答案 0 :(得分:0)
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>
答案 1 :(得分:0)
代码没关系,但是当你使用“loop_channel_name”时,取数组的最后一个元素。您必须传递实际元素(this):
document.getElementById('channel_button_'+loop_channel_name).onmouseover = function(){
alert('Rollover '+this.id);
}