2010-12-15 75 views
7

我似乎無法下轉換成現場懸停jQuery的現場徘徊

$("li.favorite_item").hover(
    function() { 
     $(this).append($(" <a href='#' class='button'>x</a>")); 
    }, 
    function() { 
     $(this).find("a:last").remove(); 
    } 
); 

我已經試過:

$("li.favorite_item"").live('hover', function() { 
    function() { 
     $(this).append($(" <a href='#' class='button'>x</a>")); 
    }, 
    function() { 
     $(this).find("a:last").remove(); 
    } 
}); 

但它不工作。

回答

29

從jQuery的1.7+ .live()是deprecated,和.delegate()一直superseded通過。對()方法。

使用.on().off()代替.live()和.die()。使用.on()代替.delegate()。

轉換舊代碼很簡單as explained here


你需要調用.hover()地圖分別,像這樣的事件:

$("li.favorite_item").live('mouseenter', function() { 
    $(this).append($(" <a href='#' class='button'>x</a>")); 
}).live('mouseleave', function() { 
    $(this).find("a:last").remove(); 
}); 

.hover()並不像.click()事件功能,例如,它是just a special shortcut for .mouseenter(handler1).mouseleave(handler2) ...所以你需要在您的通話中也要這樣做。

如果你在jQuery的1.4.3+,你可以用一個圖來簡化事情,就像這樣:

$("li.favorite_item").live({ 
    mouseenter: function() { 
    $(this).append($(" <a href='#' class='button'>x</a>")); 
    }, 
    mouseleave: function() { 
    $(this).find("a:last").remove(); 
    } 
}); 

此外,如果這是在一個特定的<ul>.delegate()是一個更好的選擇,像這樣:

$("#myUL").delegate("li.favorite_item", { 
    mouseenter: function() { 
    $(this).append($(" <a href='#' class='button'>x</a>")); 
    }, 
    mouseleave: function() { 
    $(this).find("a:last").remove(); 
    } 
}); 
5

.live()語法更好,但我們現在必須使用.on()。

您可以在文檔中使用的事件映射,與選擇的第二個參數:

$(document).on({ 
    mouseenter: function() { 
     $(this).append("<a href='#' class='button'>x</a>"); 
    }, 
    mouseleave: function() { 
     $(this).find("a:last").remove(); 
    } 
}, "li.favourite_item"); 
-1

這是真的...

$("#your_div_id").live('mouseover',function(){ 

    $(this).find(".child_div").css('background-color','#111111'); 

}).live('mouseout',function(){ 

    $(this).find(".child_div").css('background-color','#757575'); 
});