简体   繁体   English

无法循环遍历jquery创建的元素

[英]Can't loop through elements created by jquery

I've added a bunch of links to a div like this: 我已经添加了一堆链接到这样的div:

$('#links').append('<a href="http://example.com/">Example</a>');

But when I try to loop through them with $('#links a').each it only finds the links that are already there in the HTML. 但是当我尝试使用$('#links a').each遍历它们时, $('#links a').each它只找到HTML中已存在的链接。

What am I doing wrong? 我究竟做错了什么?

Your code as you've given it above works fine (tested). 您上面给出的代码工作正常(经过测试)。 That means you're doing something else that's causing the problem. 这意味着你正在做其他导致问题的事情。 Possibilities include: 可能性包括:

  • Using the wrong selector. 使用错误的选择器。
  • Appending the elements in the wrong place. 将元素添加到错误的位置。
  • Storing the value of your selector in a variable and not updating it after the new elements are appended. 将选择器的值存储在变量中,而不是在追加新元素后更新它。

My personal guess is the last one there, since it's the least obvious. 我的个人猜测是那里的最后一个,因为它是最不明显的。 But I've made all three mistakes in the past. 但我过去犯了三个错误。 Hope that helps. 希望有所帮助。

That is strange, but try viewing the DOM as it is after the manipulation in case the end HTML is not as you expect it to be. 这很奇怪,但尝试在操作之后查看DOM,以防最终HTML不像您期望的那样。 You can do this via web developer toolbar (view generated source) or via firebug. 您可以通过Web开发人员工具栏(查看生成的源)或通过firebug执行此操作。

This should work. 这应该工作。 It wouldn't work if You did something more like that: 如果你做了更像这样的事情,它将无法工作:

$('#links').append('<a href="http://example.com/">Example</a>').find('a').each();

or fetching $('#links a') before You do the appending 或者在执行追加之前获取$('#links a')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM