2010-07-09 75 views
0

我希望能夠定義變量,然後我就可以使用其他事件,如鼠標移開,了mouseenter,點擊等jQuery的變量多個事件

這是當前的代碼:

$('a div') 

    // Get the width an height of the image 
    //var $img_width = $(this).children('img').width(); 
    //var $img_height = $(this).children('img').height(); 

    .mouseenter(function() { 
     alert($img_width) 

    }) 
    .mouseleave(function() { // Animate the image back to it's original size 
     alert($img_width); 
    }) 
    .each(function(index) { 
     alert($img_width); 
    }); 
+0

你能舉出更多的例子嗎?因爲現在你可以'.bind('mouseenter mouseleave',function(){//做某事})。mouseenter()',需要更多關於你的總體目標的信息。 – 2010-07-09 10:40:15

回答

1

試試這個,它應該爲你提供你需要的事件處理,在mouseover和mouseout上。每次您將鼠標懸停在圖片上時,都可以使用$(this)來引用它,所以在這個實時處理程序中,您可以使用指定的元素執行任何想要的操作。

還有很多其他活動可以處理的事件,如果需要請閱讀。 http://api.jquery.com/live/

$('a div').live('mouseover mouseout', function(event) { 

    var $img_width = $(this).children('img').width(); 

    if(event.type == 'mouseover'){ 
     //do stuff on mouse over 
    } 
    else if(event.type == 'mouseout'){ 
     //do stuff on mouseout 
    } 

    alert($img_width); 

}); 

編輯 我看到你在div檢查孩子你有事件必然。您可能會更好地直接在事件處理程序中引用img。然後,您可以立即獲得寬度,而無需遍歷DOM。

$('a div img').live('mouseover mouseout', function(event) { 

祝你好運!

0

如果你換了一下週圍的代碼,您可以使用.each()創建你的優勢倒閉,就像這樣:

$("a div").each(function(index) { 
    var $img_width = $(this).children('img').width(); 
    var $img_height = $(this).children('img').height(); 

    $(this).mouseenter(function() { 
    alert($img_width) 
    }).mouseleave(function() { 
    alert($img_width); 
    }); 

    alert($img_width); 
}); 

You can test it out here

這定義了每個匹配元素的變量,這就是你將在綁定函數中獲得的值,特定於每個<div>就像你想要的。作爲附註,<div>(或任何塊元素)不是<a>的合法子項,因此如果可能,您可能需要重新訪問標記。