.绑定到.each循环中的dom对象
我正在使用each对DOM元素进行迭代,但是当元素在.each循环中可用时,它们将不接受jQuery绑定事件.绑定到.each循环中的dom对象,dom,javascript-events,jquery,Dom,Javascript Events,Jquery,我正在使用each对DOM元素进行迭代,但是当元素在.each循环中可用时,它们将不接受jQuery绑定事件 $('#products .page_item').mouseover(function(){ console.log('this works, adding the mouseover to every selected element'); }); $('#products .page_item').each(function(index, element){ ele
$('#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循环中的每个元素可用,以便将事件绑定到它们
谢谢大家
我以这种方式迭代元素,以便有条件地从绑定中排除一些元素,FWIW。您需要在jQuery对象中包装元素:
$(element).mouseover(function(){
元素,或者这是DOM元素,而不是jQuery对象
完整代码修复:
从:
每个方法都旨在使DOM循环构造简洁且不易出错。调用时,它会迭代作为jQuery对象一部分的DOM元素。每次回调运行时,都会从0开始传递当前循环迭代。更重要的是,回调是在当前DOM元素的上下文中触发的,因此关键字this引用元素
您需要在jQuery对象中包装元素:
$(element).mouseover(function(){
元素,或者这是DOM元素,而不是jQuery对象
完整代码修复:
从:
每个方法都旨在使DOM循环构造简洁且不易出错。调用时,它会迭代作为jQuery对象一部分的DOM元素。每次回调运行时,都会从0开始传递当前循环迭代。更重要的是,回调是在当前DOM元素的上下文中触发的,因此关键字this引用元素
请尝试以下代码:
请尝试以下代码:
$('#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'");
});
});