开发者

Dynamically added HTML elements can't be found using jQuery

开发者 https://www.devze.com 2022-12-22 17:06 出处:网络
I am implementing a tree browser in HTML. On clicking a node, I call a function that adds the node\'s child elements. So far so good. I now want to immediately invoke the click handler of one of the c

I am implementing a tree browser in HTML. On clicking a node, I call a function that adds the node's child elements. So far so good. I now want to immediately invoke the click handler of one of the child elements to expand that too. My problem is that jQuery can't find the child elements that have just been added. When I step through in the debugger, my code to find the elements is being invoked before the new elements get rendered by the browser, which I'm guessing is the problem.

Is there some event I can wait for (similar to onload maybe) that marks when the newly added HTML is开发者_如何学C visible? Or a method I can call to force the rendering to take place earlier? Any suggestions would be welcome.

Note: I have since realised that the problem was entirely my fault, not the browser's or jQuery's. Please see my answer below.


You can use .live() for this, rig your click handler to it instead of just .click() like this:

$(document).ready(function() {
  //instead of $(".myTreeNode").click(....
  $(".myTreeNode").live('click', function() {
    //Do stuff
  });
});

A .click() binds event handlers to the elements it finds when it's executed, so new elements don't have the handler. .live() instead listens up at the DOM level for clicks to bubble up, so it doesn't matter if they're added now or later. In the case of a lot of elements, you also have event handler instead of 1 for every element, after a few elements, this becomes more efficient as well.


"live" is deprecated since jquery 1.7+ so Try this,

$(document).on("click","#Cancel" , function(){
 //do something
});

Visit http://api.jquery.com/on/ for more information


I got round the problem eventually by using setTimeout() to delay my code until the new elements had been rendered. Not an ideal solution though, as the timeout period I've chosen is fairly arbitrary.

I have got to the bottom of it. The function I was calling that added the HTML was doing it asynchronously via a callback. So when I was trying to find the new HTML elements, they really weren't there yet. I have now altered my code so the callback is also responsible for processing the newly added elements, so guaranteeing that they'll be present.

0

精彩评论

暂无评论...
验证码 换一张
取 消