繁体   English   中英

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

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

我想在我的DOM上调用特定元素的函数,例如:

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

它适用于已存在于DOM中的任何元素,但我也希望在动态添加到DOM的元素中调用此方法。

我尝试过这样的事情:

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

要么:

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

但没有任何成功。

检查jsFiddle

更新

.css()调用只是一个例子,我实际上想要调用其他类型的函数

你很亲密 尝试:

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

糟糕,这不起作用。 这个http://jsfiddle.net/4Bv9r/

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

如果您知道要动态添加元素,最好的方法是将规则添加到样式表中。

或者你可以动态创建样式,

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

要么

在页面<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