How to dynamically insert an element on an element that was dynamically inserted?
I want to be able to dynamically append to an element that was dynamically appended. If you have this:
<div id="main">
</div>
$(document).ready(function() {
$('#main').append('<div id="inner"></div>');
$('#inner').append('<div id="goal"></div>');
});
#goal never gets appended. Is there a jquery function to handle this or开发者_高级运维 how would I do it?
http://jsfiddle.net/jmZY4/
Turn it on its head (live copy — there was a bug in the CSS of your example, btw, two #main rules and no #inner rule):
$(document).ready(function() {
var inner = $('<div id="inner"></div>');
inner.appendTo('#main');
inner.append('<div id="goal"></div>');
});
appendTo is kind of the converse of append.
You can write that more compactly, though (in my view) it's not worth the loss of clarity (live copy):
$(document).ready(function() {
$('<div id="inner"></div>')
.appendTo('#main')
.append('<div id="goal"></div>');
});
Of course, in your precise example, you could just (live copy):
$(document).ready(function() {
$('#main').append('<div id="inner"><div id="goal"></div></div>');
});
...but I'm guessing you have a reason for doing the two separately.
Try this
$(document).ready(function() {
$('<div id="inner"></div>').append('<div id="goal"></div>').appendTo('#main');
});
加载中,请稍侯......
精彩评论