javascript 从所有 <img> 标签中删除 onmouseover 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10739734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove onmouseover event from all <img> tags
提问by karaxuna
I doing this way:
我这样做:
$.each($('img'), function () {
this.unbind('onmouseover');
});
This does not work. Why?
这不起作用。为什么?
回答by Selvakumar Arumugam
Try like below,
尝试如下,
$('img').unbind('mouseover');
No need for looping.. and also it should be mouseover
not onmouseover
无需循环..也应该是mouseover
不onmouseover
Assumptions:You are using .bind
to bind the mouseover
handler
假设:您正在使用.bind
绑定mouseover
处理程序
I'm not using bind. some images have onmouseover attribute and I want to delete them. I tries $('img').removeAttr('onmouseover') but it still does not work
我没有使用绑定。有些图像具有 onmouseover 属性,我想删除它们。我尝试了 $('img').removeAttr('onmouseover') 但它仍然不起作用
- Using inline event handler is not a standard.
- Since you are using jQuery, you should bind handler like below.
- 使用内联事件处理程序不是标准。
- 由于您使用的是 jQuery,您应该像下面这样绑定处理程序。
Code:
代码:
$('img').on('mouseover', function () {
//Your code
});
And later can unbind them by using .off
->
稍后可以使用.off
->解除它们的绑定
$('img').off('mouseover');
A work around for what you have (not preferred), (Reference)
解决您所拥有的(非首选),(参考)
$.each($('img'), function () {
$(this).removeAttr('onmouseover');
});
回答by Joseph
No need for
$.each()
when a jQuery element collection already has an internaleach()
.Also, you can "daisy chain" remove handlers methods in jQuery since each function returns the same collection. Each attach method has it's own remove method pair, so use accordingly.
Lastly, to remove the handlers on the DOM elements (the inline event handlers), replace it with null or a function that does
return false
;
此外,您可以“菊花链”删除 jQuery 中的处理程序方法,因为每个函数都返回相同的集合。每个 attach 方法都有自己的 remove 方法对,因此请相应地使用。
最后,要删除 DOM 元素上的处理程序(内联事件处理程序),请将其替换为 null 或执行以下操作的函数
return false
;
Here's the concept code:
这是概念代码:
$('img')
.unbind('mouseover') //remove events attached with bind
.off('mouseover') //remove events attached with on
.die('mouseover'); //remove events attached with live
.each(function(i,el){ //and for each element
el.onmouseover = null //replace the onmouseover event
});