今天在使用jquery替换代码中元素的click事件,由于元素已指定绑定onclick事件,试了好几种方法都不行。
示例如下:
1 | <divonclick='alert(111)'id='demo1'></div> |
现在想通过js来动态更改 #demo1元素的click事件。
不行的代码有
1 2 3 4 5 | $('#demo1').attr('onclick',function(){alert(222)}); 及 $('#demo1').click(function(){ alert(222); }); |
在网上查找了下,有下面几种解决方法
jquery解决方法:
1 2 3 | $('#demo1').unblind('click').removeAttr('onclick').click(function(){ alert(222); }); |
js原生解决方法
1 2 3 | document.getElementById('demo1').onclick=function(){ alert(222) } 也可通过jquery来写,如 $('#demo1')[0].onclick=function(){ alert(222) } |