我使用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/