简体   繁体   English

如何修改这个jQuery语法

[英]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 : 当悬停事件被触发时,下面的例子可以工作,而当鼠标悬停事件不起作用时,它对已经存在于DOM中的元素起作用,但是当动态创建元素时,它不起作用,我意识到我需要为此使用jQuery live()或委托(),事情是我试图修改它,并且它没有产生预期的结果,这是工作代码:

$(".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. .live('hover', function() {})简写适用于$(this).children().slideToggle()东西,但是为此,您需要直接使用mouseentermouseleave事件,相同事件.hover()实际上绑定到了。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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