简体   繁体   English

如何在DOM中的每个元素中调用函数,即使它们是动态创建的

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

I want to call a function over specific elements on my DOM, for example: 我想在我的DOM上调用特定元素的函数,例如:

$(".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. 它适用于已存在于DOM中的任何元素,但我也希望在动态添加到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 检查jsFiddle

Update 更新

The .css() call is just an example I actually want to call other kind of functions .css()调用只是一个例子,我实际上想要调用其他类型的函数

You were close. 你很亲密 Try: 尝试:

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

Oops, that doesn't work. 糟糕,这不起作用。 This does http://jsfiddle.net/4Bv9r/ 这个http://jsfiddle.net/4Bv9r/

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

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 在页面<style id='d_style'></style>添加此项

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM