开发者

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 mista开发者_开发知识库ke, 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.


Make sure you are using jQuery 1.4 or later, and according to the docs, you need to use mouseenter and mouseleave rather than hover.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜