I'm trying to replace a div with created elements, going from:
<div id='links'></div>
to
<div id='links'>
<ul>
<li><a href='#'>No</a></li>
</li>
</div>
I want to attach a function to the link in the <a>
element that I create. Creating the desired link is working, but wrapping the link in an <li>
element and a <ul>
element using the wrap function isn't working:
var no = $('<a>').attr({
href: '#'
}).click(function () {
ale开发者_如何学Pythonrt('clicked no');
return false;
}).text('no');
Works, but no.wrap('<li></li>');
still just gives me an unwrapped <a>
element.
I've also tried $('#links').append('<ul>').append('<li>').append(no)
but that doesn't work either.
Is there a better way to do this?
no.wrap('<li></li>')
will still return the <a>
element, but it adds a <li>
element around it. So you can do no.wrap('<li></li>').parent()
to wrap it and return the <li>
element.
<script type="text/javascript">
$(function(){
var list = $("<ul />");
var no = $('<a />')
.attr({ href: '#' })
.click(function () {
alert('clicked no');
return false;
})
.text('no')
.wrap("<li />")
.parent()
.appendTo(list);
list.appendTo("#links");
});
</script>
With jQuery can actually just nest everything into a wrapper, especially if you don't need to address the individual items themselves.
You can also create new elements to be nested on the fly. No need to create a bunch of temporary variables to hold them all.
Multiple items can be appended at the same time by simply passing them all as separate parameters to append().
var wrapper = $('<div/>', {
id: 'links'
});
$(wrapper).append(
$('<ul/>').append(
$('<li/>').append(
$('<a/>', {
href: '#',
text: 'Yes'
})
),
$('<li/>').append(
//you can even keep going!
$('<a/>', {
href: '#',
text: 'No'
})
),
$('<li/>').append(
$('<a/>', {
href: '#',
text: 'Maybe'
})
)
)
);
精彩评论