从所有<img>标记中删除onmouseover事件

kar*_*una 4 html javascript jquery asp.net-mvc-3

我这样做:

$.each($('img'), function () {
    this.unbind('onmouseover');
});
Run Code Online (Sandbox Code Playgroud)

这不起作用.为什么?

Sel*_*gam 9

试试如下,

$('img').unbind('mouseover');
Run Code Online (Sandbox Code Playgroud)

无需循环..也应该是mouseoveronmouseover

假设:您正在使用.bind绑定mouseover处理程序

我没有使用bind.一些图像有onmouseover属性,我想删除它们.我尝试$('img').removeAttr('onmouseover')但它仍然不起作用

  1. 使用内联事件处理程序不是标准.
  2. 由于您使用的是jQuery,因此您应该像下面那样绑定处理程序.

码:

$('img').on('mouseover', function () {
     //Your code
});
Run Code Online (Sandbox Code Playgroud)

然后可以使用.off- > 取消绑定它们

$('img').off('mouseover');
Run Code Online (Sandbox Code Playgroud)

解决你所拥有的问题(不是首选),(参考)

$.each($('img'), function () {
    $(this).removeAttr('onmouseover');
});
Run Code Online (Sandbox Code Playgroud)


Jos*_*eph 5

  • $.each()当jQuery元素集合已经具有内部时,不需要each().

  • 此外,您可以"菊花链"删除jQuery中的处理程序方法,因为每个函数都返回相同的集合.每个attach方法都有自己的remove方法对,因此请相应使用.

  • 最后,要删除DOM元素(内联事件处理程序)上的处理程序,请将其替换为null或函数return false;

这是概念代码:

$('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
    });
Run Code Online (Sandbox Code Playgroud)