我是jQuery的新手,但我已经知道了:
$('div.team_text').each(function() {
$('<a>', {
"href" : $(this).attr("id"),
"text" : $(this).find("h3").text()
}).appendTo('ul.tabs');
});
这为我提供了我需要的链接,这些链接来自包含<h3>
s的人名的div
:
<a href="teamBod2">Person Name</a>
但我需要生成的是:
<li><a href="teamBod2">Person Name</a></li>
如何更改我的 jQuery?
您可以使用
.wrap()
}).wrap("<li/>").parent().appendTo('ul.tabs');
请注意在 wrap
之后调用 parent
,因为wrap
返回原始的 jQuery 对象(在您的情况下是链接),但我们想要做的是将li
(及其新包装的链接)附加到列表中。
tymeJV 似乎很好地捕捉到了它。只是根据缓存选择器和更新 DOM 建议的一些更改。
var $h = $("<div>");//create a holder for the new elements
$('div.team_text').each(function() {
var $this = $(this);//cache 'this'
$h.append(
$('<a>').attr({//I use the attr method to add the properties, I think that it is easier to read.
"href" : $this.attr("id"),
"text" : $this.find("h3").text()
}).wrap("<li>")
);
});
$('ul.tabs').append($h.children());
如果这个答案没有增加价值,我会删除它!