JavaScript如何给HTML元素动态绑定onclick和hover事件?

JavaScript如何给HTML元素动态绑定onclick和hover事件?

JavaScript使用getElementsByClassName获取所有指定类名的HTML元素,然后使用for循环遍历逐个添加事件,这里要注意每个元素的事件是否存在共享数据的情况,普通添加事件的情形所有元素都会共享一个数据,若需要各自使用不同的数据,这时则需要使用闭包传值,达到每个元素都使用不同数据的目的。

1、动态绑定onclick事件:

var items = document.getElementsByClassName("item");

// 动态绑定onclick事件
// 使用for循环遍历,注意要使用立即执行函数和闭包才能生效
for(var i = 0;i < items.length;i++){
    (function(j){
        items[j].onclick = function(){
            console.log("click: " + j);
        }
    })(i);
}

2、动态添加hover事件:

// 动态绑定hover事件
for(var i = 0;i < items.length;i++){
    (function(j){
        items[j].onmouseover = function(){
            this.style.color = "#ffe573";
        };
        items[j].onmouseout = function(){
            this.style.color = "#fff";
        };
    })(i);
}

效果如下:

JS动态添加事件效果

来源:

https://www.srcmini02.com/912.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_42472.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?