Can I remove inline event handlers using jQuery?

走远了吗. 提交于 2019-11-27 03:20:19

问题


I have some HTML with an onclick attribute. I want to override that attribute using jQuery. Is there any way to remove the click handler using jQuery? Using unbind doesn't work.


回答1:


Try the .removeAttr() function:

$(function() {
    $('a').removeAttr('onclick');
});

​ jsfiddle demo.

Once you've got rid of the onclick attribute you could attach your own click handler.




回答2:


$("#theElement")[0].onclick = function() {
  whatever();
};
// -- or --
$("#theElement")[0].onclick = null;

It's not that jQuery would make the standard DOM functions and properties go away. ;-)




回答3:


As quoted in http://api.jquery.com/prop/ Removing an inline onclick event handler using .removeAttr() doesn't achieve the desired effect in Internet Explorer 8, 9 and 11. To avoid potential problems, use .prop() instead.

So this can be done as

$(function() {
    $('a').prop('onclick', false);
});



回答4:


There is a plugin for it, but you should only do this when you really need to. The plugin gives you the option to call the old function or to ignore it entirely.

jQuery Override Plugin

$(divElementObj).override('onclick', 'click', function(...));



回答5:


Tried given options but worked partially as they removed one but not all.

Instead I tried following chaining as workaround. I am using ver 1.4.2.

jQuery("selector")
    .removeAttr("onclick").removeAttr("onmouseout").removeAttr("onmouseover");


来源:https://stackoverflow.com/questions/3846263/can-i-remove-inline-event-handlers-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!