【问题标题】:Two asynchronous events the second depending on the first两个异步事件,第二个取决于第一个
【发布时间】:2012-10-22 21:01:20
【问题描述】:

我正在像这样的.on() jquery 处理程序上创建一些东西

$('#idhere').on('click', function(){
   //create a couple of divs with a class
   });

现在我还想在创建的 div 上添加一个事件,我试过了:

$('.divcreated').bind('mouseover', function(){
   //do some magic
   });

由于某种原因,第二个事件永远不会被触发,可能是因为它们都是异步的。有什么想法可以触发第二个事件吗?

【问题讨论】:

  • 第二个事件永远不会发生,因为当您尝试选择它们时元素不存在。在创建元素时绑定事件,或者使用事件委托。

标签: jquery ajax events asynchronous event-handling


【解决方案1】:

正如已经说过的,当您尝试注册 mouseover 事件时,不会创建新的 div。因此,您可以为一个 div 尝试这样的操作:

$('#idhere').on('click', function(){

   // creates the new div and assigns it to the $myNewDiv var
   var $myNewDiv = $( "<div></div>" );

   // register the event...
   $myNewDiv.on( "mouseover", function( event ) { ... }); 

   // add $myNewDiv to a container

});

我认为现在您可以编写自己的解决方案了。

【讨论】:

  • 所以这里的想法是将所有 div 分组并将事件赋予分组 div,不是吗?也只是将一个事件嵌套在另一个事件中,就可以随时触发嵌套的事件?
【解决方案2】:

绑定时元素必须存在,因此您必须在创建元素后绑定它或使用委托 -

使用委托 jQuery 1.7+

$('body').on('mouseover', '.divcreated', function(){
       //do some magic
});

这将事件处理程序绑定到 body - 在您绑定事件时存在 - 已准备好 dom。不过,它更有效地绑定到更接近的静态父元素。

【讨论】: