浏览器中的观察者模式-javascript:订阅事件“添加了Dom元素”并处理此元素

时间:2021-12-14 00:10:00

I have a query:

我有一个问题:

$(function() {
    $('form').each(function() {
      // do smthing with form
    });
});

Forms may appear dynamically, i.e. built by javascript. I need to handle them just after load, smth like:

表单可以动态显示,即通过javascript构建。我需要在加载后处理它们,如:

$('form').onload(function() {
   // it's called after new form was added to dom
});

I thought about using setInterval, but maybe HTML5 or new ES standards brought smth new...

我想过使用setInterval,但也许HTML5或新的ES标准带来了新的...

Does anybody help to compose on load callback with aforementioned characteristics?

有没有人帮助组成上述特征的负载回调?

P.S. To clarify the purpose: I need to attach event handler to event "element was added to dom".

附:澄清目的:我需要将事件处理程序附加到事件“元素被添加到dom”。

2 个解决方案

#1


1  

Actually there was an event which is deprecated by now called "DOMNodeInserted", it would be wise to use delegated events. with delegated events you can handle events on new elements that are dynamically add to DOM.

实际上有一个被现在称为“DOMNodeInserted”的事件已被弃用,使用委托事件是明智的。使用委派事件,您可以处理动态添加到DOM的新元素上的事件。

#2


1  

Wrap it in a function

将它包装在一个函数中

$(function() {
    function modForm() {
    $('form').each(function() {
      // do smthing with form
    });
    }
   modForm();
  $('a').click(function(){
    //add form dynamically
    $('body').append('<form>');
    //call the function agan
     modForm();
  });
});

#1


1  

Actually there was an event which is deprecated by now called "DOMNodeInserted", it would be wise to use delegated events. with delegated events you can handle events on new elements that are dynamically add to DOM.

实际上有一个被现在称为“DOMNodeInserted”的事件已被弃用,使用委托事件是明智的。使用委派事件,您可以处理动态添加到DOM的新元素上的事件。

#2


1  

Wrap it in a function

将它包装在一个函数中

$(function() {
    function modForm() {
    $('form').each(function() {
      // do smthing with form
    });
    }
   modForm();
  $('a').click(function(){
    //add form dynamically
    $('body').append('<form>');
    //call the function agan
     modForm();
  });
});