【问题标题】:How to make jQuery 1.7 .on() hover?如何让 jQuery 1.7 .on() 悬停?
【发布时间】:2012-07-17 12:15:53
【问题描述】:

我在悬停状态下动态创建的元素有问题。当我将鼠标悬停在新创建的 html 元素上时,它不起作用。

这是我的 HTML 代码:

<button id="create">create new button</button>
<button class="hover">hover me</button>
<div></div>

jQuery:

var createBtn = $("#create");

createBtn.click(function() {
    $('div').append('<button class="hover">new hover button</button');  
    return false;        
}); 


$('.hover').hover(function() {
    alert('you hovered the button!');
}, function() {
    alert('you removed the hover from button!');
});

我什至试过这个代码:

$('.hover').on({
    mouseenter : function() {
         alert('you hovered the button!');
    },
    mouseleave : function() {
        alert('you removed the hover from button!');
    }

});

如此处所示http://api.jquery.com/on/,但仍然没有运气。 这里还有演示:http://jsfiddle.net/BQ2FA/

【问题讨论】:

标签: jquery hover


【解决方案1】:

这不是正确的语法。

使用它来监听动态创建的“.hover”元素的事件:

$(document).on('mouseenter', '.hover',  function(){
         alert('you hovered the button!');
}).on('mouseleave', '.hover', function() {
        alert('you removed the hover from button!');
});

【讨论】:

  • .on() 的第一个参数仍然可以是一个对象(正如 OP 当前所做的那样),如果您想避免多次显式调用它。 (投反对票不是我的 - 这个答案仍然是正确的)。
  • @JamesAllardice 有很多可能的解决方案,我同意可以缩短,但 OP 的调用不适用于动态创建的“.hover”元素,这就是我修复的。
  • 我知道,我只是指出了一个事实,即 OP 不必更改那么多 - 他们只需更改初始选择器并添加 .hover 选择器作为第二个参数事件名称和事件处理程序的映射。他们不必将其更改为对.on() 的两次单独调用。 (该评论是为了 OP 的利益,而不是对您的回答的批评)。
  • 是的,没错。我不会更改我的代码,因为这是一个细节,Esalija 已经给出了这个变体,但感谢你的精确性:提醒我替代语法对我也有好处(不仅是 OP)。
【解决方案2】:

您正在使用.on进行直接绑定,您需要使用它进行委托:

$('div').on({
    mouseenter: function() {
        alert('you hovered the button!');
    },
    mouseleave: function() {
        alert('you removed the hover from button!');
    }
}, ".hover");

http://jsfiddle.net/BQ2FA/2/

【讨论】:

    猜你喜欢
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 2012-04-07
    • 1970-01-01
    相关资源
    最近更新 更多