jQuery的某些类的div检测已添加到DOM [英] jquery detecting div of certain class has been added to DOM

查看:120
本文介绍了jQuery的某些类的div检测已添加到DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.on()绑定页面加载后创建的div事件.它可以很好地用于单击,mouseenter ...,但是我需要知道何时添加了MyClass类的新div.我正在寻找这个:

I'm using .on() to bind events of divs that get created after the page loads. It works fine for click, mouseenter... but I need to know when a new div of class MyClass has been added. I'm looking for this:

$('#MyContainer').on({

  wascreated: function () { DoSomething($(this)); }

}, '.MyClass');

我该怎么做?我已经设法在没有插件的情况下编写了整个应用程序,我希望保持这种状态.

How do I do this? I've managed to write my entire app without a plugin and I want to keep it that way.

谢谢.

推荐答案

3年后的经验,这就是我如何收听将某个类的元素添加到DOM中" 的方法:在jQuery html()函数中添加一个钩子,如下所示:

3 years of experience later, this is how I listen to "element of a certain class added to the DOM": you simply add a hook into the jQuery html() function, like this:

function Start() {

   var OldHtml = window.jQuery.fn.html;

   window.jQuery.fn.html = function () {

     var EnhancedHtml = OldHtml.apply(this, arguments);

     if (arguments.length && EnhancedHtml.find('.MyClass').length) {

         var TheElementAdded = EnhancedHtml.find('.MyClass'); //there it is
     }

     return EnhancedHtml;
   }
}

$(Start);

如果您使用的是jQuery,则此方法有效.而且它不依赖于浏览器特定的事件DOMNodeInserted,该事件与跨浏览器不兼容.我还为.prepend()

This works if you're using jQuery, which I do. And it doesn't rely on the browser-specific event DOMNodeInserted, which is not cross-browser compatible. I also added the same implementation for .prepend()

总的来说,这对我来说就像一种魅力,希望对你也一样.

Overall, this works like a charm for me, and hopefully for you too.

这篇关于jQuery的某些类的div检测已添加到DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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