【问题标题】:how to make .hover() works with.on()? [duplicate]如何使.hover() 与.on() 一起工作? [复制]
【发布时间】:2014-01-07 18:35:48
【问题描述】:

我有一个动态的 HTML 内容

<div id="parent">
    <div class="child">
        Hover Text
    </div>
</div>

当我尝试使用此代码将“悬停文本”悬停在子元素内时,它不起作用。

$("#parent").on('hover', '.child', function()
{
    alert("Hello");
});

这段代码也没有

$('#parent').on('hover', '.child', function(e) {
    ...
});

我使用 jq 与 1.10.2

【问题讨论】:

标签: jquery html


【解决方案1】:

如果整个div#parent块是动态生成的,您可能需要将hover监听器绑定到文档本身,如下所示。

另外,我建议使用 mouseentermouseleave 侦听器,因为在 jQuery 1.9 中删除了 hover 简写。

在 jQuery 1.8 中已弃用,在 1.9 中删除:名称“hover”用作 字符串“mouseenter mouseleave”的简写。

这是我的示例:

jQuery(document).on('mouseenter', '#parent .child', function (e) {
    jQuery(this).css('backgroundColor','#F00');
}).on('mouseleave', '#parent .child', function (e) {
    jQuery(this).css('backgroundColor','#FFF');
});

http://jsfiddle.net/UX8z5/1/

【讨论】:

    【解决方案2】:

    尝试使用on() 添加mouseentermouseleave 事件。 这是一个例子:

    $(function(){
        $("#parent").on({
            mouseenter : function(e){
                alert("Mouse enter");
            },
            mouseleave : function(e){
                alert("Mouse leave");
            }
        }, ".child");
    });
    

    jsfiddle:http://jsfiddle.net/ashishanexpert/2XG9j/

    【讨论】:

      【解决方案3】:

      您可以使用.hover() 方法为 mouseenter 和 mouseleave 事件绑定处理程序。您可以使用它在鼠标位于元素内时简单地将行为应用于元素。

      $(document).ready(function(){
         $('#parent .child').hover(function(){
          alert("Hello");
         });
      });
      

      Try in .hover() in Jsfiddle

      你也可以使用.mouseover()事件。

      $(document).on('mouseover', '#parent .child', function(){
          alert("Hello");
      });
      

      Try mouseover event handler fiddle

      但这里的最佳做法是将 mouseentermouseleave 事件与事件委托绑定。

      $(document).ready(function(){
          $('#parent').on({
              mouseenter: function() {
                  alert('Hello');
              },
              mouseleave: function() {
                  alert('bye..!!!');
              }
          }, ".child");
      });
      

      Try in fiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-16
        • 2019-11-21
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多