如何在DOM中的每个元素中调用函数,即使它们是动态创建的 [英] How to call a function in every element in the DOM even if they are dynamically created

查看:150
本文介绍了如何在DOM中的每个元素中调用函数,即使它们是动态创建的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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.

我尝试过这样的事情:

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

或:

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

但没有任何成功。

检查 jsFiddle

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

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

推荐答案

你很接近。尝试:

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

哎呀,这不起作用。这可以 http://jsfiddle.net/4Bv9r/

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

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

这篇关于如何在DOM中的每个元素中调用函数,即使它们是动态创建的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆