使用jQuery无法找到动态添加的HTML元素

问题描述:

我正在用HTML实现树形浏览器.单击节点时,我调用一个添加节点的子元素的函数.到目前为止,一切都很好.现在,我想立即调用子元素之一的点击处理程序,以进行扩展.我的问题是jQuery无法找到刚刚添加的子元素.当我逐步进入调试器时,我的代码来查找元素是在浏览器呈现新元素之前调用的,我猜这是问题所在.

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.

我是否可以等待某些事件(可能类似于onload)来标记何时可以看到新添加的HTML?还是我可以调用的强制渲染提早进行的方法?任何建议都将受到欢迎.

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

注意:从那以后,我意识到问题完全是我的错,而不是浏览器或jQuery的错.请在下面查看我的答案.

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

我最终通过使用setTimeout()将代码延迟到呈现新元素之前解决了这个问题.不过,这并不是理想的解决方案,因为我选择的超时时间相当随意.

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.

我已经了解到了.我调用的添加HTML的函数是通过回调异步完成的.因此,当我尝试查找新的HTML元素时,它们确实还不存在.现在,我已经更改了代码,因此回调函数还负责处理新添加的元素,从而保证它们将存在.

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.