首页javascriptmouseJavascript Event - 如何在动态创建的html元素上创建鼠标悬停处理程序

Javascript Event - 如何在动态创建的html元素上创建鼠标悬停处理程序

我们想知道如何在动态创建的html元素上创建鼠标悬停处理程序。

<!DOCTYPE html>
<html>
<body>
  <div id="channels_buttons_container"></div>
<script type='text/javascript'>

channels_array = ["red", "green", "black"];
for(var i = 0; i < channels_array.length; i++) {
    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>test';
    document.getElementById('channels_buttons_container').appendChild(new_button_element);

    document.getElementById('channel_button_'+loop_channel_name).onmouseover = function(){
        document.writeln('Rollover '+this.id);
    }
}

</script>
</body>
</html>