繁体   English   中英

如何修改这个jQuery语法

[英]how to modify this jquery syntax

当悬停事件被触发时,下面的例子可以工作,而当鼠标悬停事件不起作用时,它对已经存在于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();
                 }    
                     );

这是我想添加直播但未产生正确结果的地方:

$(".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();
                 }    
                     );

我在哪里弄错了,谢谢

你可以这样做:

$(".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();
});

.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