【问题标题】:jQuery: attach an event immediately after setting up the HTML contentjQuery:设置 HTML 内容后立即附加一个事件
【发布时间】:2011-07-13 14:10:33
【问题描述】:

首先,这是我在函数中用于分页的 jQuery 代码示例:

// new_content is a variable that holds the html I want to add to a div
$('div#my_div').html(new_content);
$("div#my_div a.details").hover(function(){         
    $(this).fadeIn(); //code to execute when the mouse get in
}, function(){
    $(this).fadeOut(); //code to execute when the mouse get out
});  

但是悬停事件根本不起作用,我相信这是因为 DOM 还没有准备好!

为了解决这个问题,我设置了一个这样的计时器:

$('div#my_div').html(new_content);

window.setTimeout(
  $("div#my_div a.details").hover(function(){           
    $(this).fadeIn(); //code to execute when the mouse get in
  }, function(){
    $(this).fadeOut(); //code to execute when the mouse get out
  });
,100); 

我问这个问题是因为我确定这不是在 html 方法之后立即附加事件的正确方法(也许它不起作用!)。

我希望有人告诉我正确的方法。

【问题讨论】:

    标签: jquery javascript-events javascript


    【解决方案1】:

    您会想要使用直播的mouseover mouseleave 活动

    $("div#my_div").live({
           mouseenter: function()
           {
    
           },
           mouseleave: function()
           {
    
           }
        }
    );
    

    或者你可以这样做:

    $('div#my_div').live('mouseover mouseout', function(event) {
        if (event.type == 'mouseover') {
            // do something on mouseover
        } else {
            // do something on mouseout
        }
    });
    

    更新

    在较新版本的 jQuery 中,您可以这样做

    $('body').on('mouseover','#my_div', function(){});
    $('body').on('mouseout', '#my_div', function(){});
    

    【讨论】:

      【解决方案2】:

      也许您需要使用live() 方法。如您所见here,您似乎需要将这两个事件分开:

      .live("mouseenter", function() {...})
      .live("mouseleave", function() {...});
      

      更新:有人投票支持我,所以如果有人到这里,我建议阅读on() 文档(here),因为live 很久以前就被弃用了。此外,看到mouseenter()(link) 和mouseleave() (link) 可能会很有趣。这个想法和live一样。

      【讨论】:

        【解决方案3】:

        最好使用代理而不是 live,因为 live 本质上是 document.body 上的代理,导致它必须冒泡更长的时间。

        这是一个使用委托的示例:http://jsfiddle.net/Akkuma/wLDpT/

        【讨论】:

        • 首先谢谢您,我刚刚尝试了您的示例,很好,我将在文档中查看详细信息。
        • 您的代码只执行 else 块中的指令,所以我通过 mouseover 更改了 mouseenter,现在它可以正常工作了。
        【解决方案4】:

        你可以查看 jquery 的 .live 函数。链接在这里 http://api.jquery.com/live/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-08
          • 2016-07-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多