running javascript on a page element that was created via ajax
I am using Javascript to make some changes to 开发者_Go百科how a page displays depending on what the user inputs in the form. This works fine and dandy, except for on one element. That is because this element is changing via ajax depending on what the user selects earlier in the form.
I am using document.observe('dom:loaded', function() {
to run my JS code, so obviously this one elements JS isnt working because the elements are added in after the dom loaded. What's the best way to run JS on this page element after they are loaded in?
Thanks!
You can handle events on the parent element, then when the event triggers you use the target property
of the event object
to find out in which child element the event was fired, for instance if you wanted to know when a button added dynamically was clicked you could do:
document.getElementById("parent").click = function(event){
if(event.target.id=="myButton"){
//handle click
}
}
<div id="parent">
<input type="button" id="myButton" /> <!-- added dinamycally -->
</div>
This is making use of Event bubbling
精彩评论