简体   繁体   中英

how to modify this jquery syntax

this example below works when hover event is trigered and when its not, its working for elements already in DOM, but when element created dynamically it doesn't work, I realize I need to use jQuery live() or delegate() for this, the thing is I tried to modify it and its not producing the results as expected, here is the working code :

$(".sidebar li").hover(
         function(){
        $(this).css("background-color", "#F9F4D0");
        $(this).append($('<button class="promoter" type="button" title="Active promotion"></button>'));
                  },
        function(){
        $(this).css("background-color", "#F9FAFA");
        $(this).children("button").remove();
                 }    
                     );

Here is the bit when I wanted to add live but it's not producing correct results :

$(".sidebar li").live('hover', function(){
        $(this).css("background-color", "#F9F4D0");
        $(this).append($('<button class="promoter" type="button" title="Active promotion"></button>'));
                  },
        function(){
        $(this).css("background-color", "#F9FAFA");
        $(this).children("button").remove();
                 }    
                     );

Where did I made mistake, thank you

You can do this:

$(".sidebar li").live('mouseenter', function(){
    $(this).css("background-color", "#F9F4D0");
    $(this).append($('<button class="promoter" type="button" title="Active promotion"></button>'));
}).live('mouseleave', function(){
    $(this).css("background-color", "#F9FAFA");
    $(this).children("button").remove();
});

The .live('hover', function() {}) shorthand works for things like $(this).children().slideToggle() or something, but for this you need to use the mouseenter and mouseleave events directly, the same events .hover() actually binds to.

确保您使用的是jQuery 1.4或更高版本,并且根据docs ,您需要使用mouseenter和mouseleave而不是将鼠标悬停。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM