创建元素时触发事件 [英] Triggering an event when an element is created

查看:82
本文介绍了创建元素时触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在DOM中调用一个函数创建新的部门(即通过ajax调用动态创建)。我知道我可以使用live方法来触发函数。但是我应该在实时方法中使用事件?我的意思是当动态创建新的分区时甚至会触发哪个?

I wanna call a function on creation of new divisions in the DOM (i.e. created dynamically thru ajax call) .I know I can use live method for triggering the function. But what event should I use in the live method? I mean which even would be triggered when a new division is dynamically created?

推荐答案

您可以使用 DOMNodeInserted 突变事件,但请注意它们已被弃用,并且在所有浏览器中都不受支持。

You can use the DOMNodeInserted mutation event, but be aware that they are deprecated and not supported in all browsers.

更好的解决方案是编写自定义事件,例如:

Better solution would be to write a custom event like:

$('#container').bind('MyAddEvent', function(){
    alert('Was added');
});

如果您希望事件也应用于新元素,请使用 on

If you want the event to be applied to new elements as well, use on:

$('#container').on('MyAddEvent', '{selector}' ,function(){
    alert('Was added');
});

当你添加新的< div> (在ajax请求之后),使用触发该事件触发

And when you add new <div> (after ajax requests), Trigger that event with trigger:

...
success: function(result){
    $('#container').append(result)
    ...
    ...
    $('#container').trigger('MyAddEvent');
} 




  • 请注意直播已弃用,上的是新人。

    • Note that live is deprecated, on is the new guy.
    • 如果你不控制新的 div s插入,你可以在每个x时间检查DOM以获得新的div :

      If you don't control the new divs insertion , you can inspect the DOM on each x time for new divs:

      function checkForChanges()
      {
          var newDivs = $('#container div').filter(function(){
                  return !$(this).data('old')
              });
      
          ... //Do what you want with those divs      
      
          newDivs.data('old', true); // mark the div as old.
      
          setTimeout(checkForChanges, 1000); // Check the DOM again within a second.
      }
      
      $(checkForChanges);
      

      这篇关于创建元素时触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆