jquery - .bind 到 .each 循环中的 dom 对象

标签 jquery dom jquery-events

我使用each迭代DOM元素,但是当这些元素在.each循环内可用时,它们将不接受jQuery绑定(bind)事件。

$('#products .page_item').mouseover(function(){
   console.log('this works, adding the mouseover to every selected element');
});

$('#products .page_item').each(function(index, element){
    element.mouseover(function(){
        console.log("this throws 'not a function'");
    });
});

如何使每个元素在 .each 循环中可用,以便我可以将事件绑定(bind)到它们?

(我以这种方式迭代元素,这样我就可以有条件地从绑定(bind)中排除一些元素,FWIW。)

最佳答案

您需要将 element 包装在 jQuery 对象中:

$(element).mouseover(function(){

element(或this)是 DOM 元素,而不是 jQuery 对象。

已修复完整代码:

$('#products .page_item').each(function(index, element){
    $(element).mouseover(function(){
        console.log("This works!");
    });
});

来自each docs :

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

关于jquery - .bind 到 .each 循环中的 dom 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10840595/

相关文章:

javascript - 从 iFrame 内部加载的外部页面访问 IFrame 元素

javascript - 在不可滚动的 Div 内捕获鼠标滚轮滚动

javascript - 按顺序切换多个 div

javascript - 简单的自定义 JavaScript 滚动条

javascript - 使用 DOM 方法删除图像元素

javascript - 从 div 内的 p 标签中选择一个值

javascript - 如何仅删除实例中添加的事件处理程序?

javascript - 如何检测文档是否回到焦点?

javascript - 有没有办法在单击特定按钮时将当前页面保存为书签,并将该页面链接作为书签保存到用户个人资料中?

javascript - jQuery promise 出现意外的 "then"调用顺序