Jquery - run function when DOM element is added

假如想象 提交于 2019-12-18 05:18:22

问题


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

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

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

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

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

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.

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


回答1:


You need to do this manually after appending new elements. Delegates and live events are only for events that bubble up.

However, you could make life more easier by listening for some of the DOM events to get a notification when a new element has been added.




回答2:


You can achieve this a couple of ways:

1) Use Mutation Events or Observers

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

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) Use the CSS Keyframe Animation event method I devised to detect DOM node insertions

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/




回答3:


You could create a simple function like this:

function AddButton (parent, buttonElement) {
    $(buttonElement).addClass('.ToButton').appendTo($(parent)).button();
}

Use like

AddButton('body', '<span>Test Button</span>');

Not the nicest way, but you could also create a simple jQuery plugin or something like that. I just presented a general idea (I put it like this because you used a function built in a similar way).

Of course the best would be to use DOM events, but thanks to IE we cannot.




回答4:


uhm, not sure if I got it right, but doesn't this work?:

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

just for your refference: http://www.bennadel.com/blog/1751-jQuery-Live-Method-And-Event-Bubbling.htm



来源:https://stackoverflow.com/questions/5753362/jquery-run-function-when-dom-element-is-added

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