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');

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

Thanks.

推荐答案

3年后,我是这样听"element of a certain class added to the DOM"的:您只需在jQuery html()函数中添加一个钩子,如下所示:

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);

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相关问答推荐

这是否会导致内存泄漏?

jquery如何判断ajax调用的响应类型

jQuery中的多个 Select 器链接?

jQuery单击/切换两个功能

自动完成时触发的任何事件?

如何制作 AngularJS 指令来停止传播?

我们如何在不重新加载页面的情况下使用 javascript/jQuery 更新 URL 或查询字符串?

仅在 _some 字段上通过 Enter 键禁用表单提交

如何使用jQuery找到元素顶部的垂直距离(以px为单位)

动态设置 iframe src

延期与promise

数字键盘的keyCode值?

使用 jQuery 验证插件自定义日期格式

使用 jQuery 从 AJAX 响应(json)构建表行

jQuery 插件:添加回调功能

如何使用 requirejs 使 jQuery 插件可加载

禁用 jquery Select 的下拉菜单

jQuery - 确定输入元素是文本框还是 Select 列表

jQuery:如何找到父母的特定子元素?

使用 jQuery 和 CSS 将数字转换为星级显示