jQuery-添加DOM元素时运行功能 [英] Jquery - run function when DOM element is added

查看:102
本文介绍了jQuery-添加DOM元素时运行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有jQuery和jQuery UI的网站.我有一个Javascript函数:

I have a website with jQuery and jQuery UI. I have a Javascript function:

function ToButton()
{
$(".ToButton").button();
}

此函数在页面加载后运行,并更改类为"ToButton"的所有元素.

This function runing after the page load and change all elements with class "ToButton".

当用户按下按钮时,我也会更改HTML代码.例如:

Also I change HTML code when user press a button. E.g.:

$("body").append('<span class="ToButton">Test Button</span>');

我也想对这个新元素运行ToButton函数,但是jQuery中的实时或委托方法没有显示"或创建"事件类型.因此,在所有HTML代码更改之后,我需要调用函数ToButton().

And I want to run ToButton function to this new element too, but live or delegate methods in jQuery don't have "show" or "create" event type. So I need call function ToButton() after all HTML code changes.

您能帮我怎样将ToButton函数委托给所有元素?

Can you help me, how I can delegate ToButton function to all elements?

推荐答案

您可以通过以下两种方法实现此目的:

You can achieve this a couple of ways:

1)使用变异事件或观察者

第一种方法很容易查找,您可以在此处找到有关DOM级别3突变事件的更多信息: http://help.dottoro.com/ljmcxjla.php -以及此处的新DOM Level 4突变观察者:

The first method is easy to look-up, you can find more on DOM Level 3 Mutation Events here: http://help.dottoro.com/ljmcxjla.php - and new DOM Level 4 Mutation Observers here: https://developer.mozilla.org/en-US/docs/DOM/MutationObserver

虽然DOM Level 3突变事件现已得到广泛支持,但它们是已弃用的API,可能会破坏某些浏览器的性能.下面的#2使用了一种方法,该方法可在所有支持CSS动画的浏览器中使用,并且不会影响性能.

While DOM Level 3 Mutation Events are widely supported now, they are a deprecated API that can kill performance in certain browsers. #2 below uses a method that works in all browsers that support CSS Animations, and it doesn't hurt performance.

2)使用我设计的CSS关键帧动画事件方法来检测DOM节点插入

每当通过浏览器的内部CSS样式机制解析节点时,您都​​可以使用虚拟关键帧动画事件使插入事件通知冒泡,我在此处写了一篇非常详细的文章:

You can use a dummy keyframe animation event to bubble up an insertion event notification whenever a node is parsed by the browser's internal CSS styling mechanisms, I wrote a very detailed post on this here: http://www.backalleycoder.com/2012/04/25/i-want-a-damnodeinserted/

这篇关于jQuery-添加DOM元素时运行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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