How to call a function in every element in the DOM even if they are dynamically created

六月ゝ 毕业季﹏ 提交于 2019-12-08 00:48:02

问题


I want to call a function over specific elements on my DOM, for example:

$(".red").css({backgroundColor: "pink"});

It works ok for any element already existing into the DOM, but I also want to this method to be called in elements dynamically added to the DOM.

I've tried things like:

$(".red").on(function(){ this.css({backgroundColor: "pink"}) });

or:

$(".red").on("load", function(){ this.css({backgroundColor: "pink"}) });

But not any success.

Check the jsFiddle

Update

The .css() call is just an example I actually want to call other kind of functions


回答1:


You were close. Try:

$(document).on("load", ".red", function(){ this.css({backgroundColor: "pink"}) });

Oops, that doesn't work. This does http://jsfiddle.net/4Bv9r/

$('body').on('DOMNodeInserted', ".red", function(){ $(this).css({backgroundColor: "pink"}) });



回答2:


If you know the element is going to be added dynamically, the best way should be adding the rules to a stylesheet.

OR you can create style dynamically,

$("<style>").text(".red { background-color: pink; }").appendTo("head");

OR

Add this in your page <style id='d_style'></style> then

$('#d_style').text(".red { background-color: pink; }");


来源:https://stackoverflow.com/questions/18643898/how-to-call-a-function-in-every-element-in-the-dom-even-if-they-are-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!