I've added a bunch of links to a div like this:
$('#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.
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. You can do this via web developer toolbar (view generated source) or via 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
精彩评论