2012-05-31 50 views
2

我使用每個元素迭代DOM元素,但是當元素在.each循環中可用時,它們將不接受jQuery綁定事件。。在每個循環中綁定dom對象

$('#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的元素。)

回答

4

你需要用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

的。每個()方法被設計成使DOM循環結構簡潔和不易出錯。 當被調用時,它遍歷屬於jQuery對象一部分的DOM元素。每次回調運行時,都會通過當前循環迭代,從0開始。更重要的是,回調在當前DOM元素的上下文中觸發,因此關鍵字this指的是元素。

0

試試這個代碼:

$('#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'"); 
    }); 
});