Jquery 将数组追加到列表项(一对一)
我的名单目前的结构如下:Jquery 将数组追加到列表项(一对一),jquery,html,append,each,Jquery,Html,Append,Each,我的名单目前的结构如下: <ul id="list-items"> <li class="cat"> <a href="#">Cat #1</a> (2) <ul class="children"> <li class="child-cat"> <a title="#">Sub cat #1</a> (1) </
<ul id="list-items">
<li class="cat">
<a href="#">Cat #1</a>
(2)
<ul class="children">
<li class="child-cat">
<a title="#">Sub cat #1</a>
(1)
</li>
</ul>
</li>
<li class="cat">
<a href="#">Cat #2</a>
(2)
<ul class="children">
<li class="child-cat">
<a title="#">Sub cat #2</a>
(1)
</li>
</ul>
</li>
</ul>
对于我的上一个任务,我需要将上述输出附加到列表项的每个锚定标记。所以我试了一下:
var b = [];
jQuery('#list-items li').each(function() {
b = jQuery(this).first().contents().filter(function() {
return this.nodeType == 3;
}).text();
});
jQuery('#list-items li a').append(function(i) {
jQuery(this).append(b[i]);
});
这似乎不起作用。我不知道为什么。。有人能帮我修改脚本吗?谢谢。一个简单的解决方案
jQuery('#list-items li > a').append(function() {
var next = this.nextSibling;
if(next){
return $.trim($(next).text())
}
});
演示:
如果要创建数组b
,我建议使用.map()
而不是.each()
演示:
代码的问题是,在第一个each循环中,您覆盖了b
,而不是将值添加到数组b
var b = [];
jQuery('#list-items li').each(function() {
b.push(jQuery(this).first().contents().filter(function() {
return this.nodeType == 3;
}).text());
});
jQuery('#list-items li a').append(function(i) {
jQuery(this).append($.trim(b[i]));
});
演示:一个简单的解决方案
jQuery('#list-items li > a').append(function() {
var next = this.nextSibling;
if(next){
return $.trim($(next).text())
}
});
演示:
如果要创建数组b
,我建议使用.map()
而不是.each()
演示:
代码的问题是,在第一个each循环中,您覆盖了b
,而不是将值添加到数组b
var b = [];
jQuery('#list-items li').each(function() {
b.push(jQuery(this).first().contents().filter(function() {
return this.nodeType == 3;
}).text());
});
jQuery('#list-items li a').append(function(i) {
jQuery(this).append($.trim(b[i]));
});
演示:我将尝试一下,看看效果如何。Thanks@user2772219n你选了哪一个?我先用我的解决方案试了一下。然后选择你的,因为它更简单,更短。我会尝试一下,看看它如何进行。Thanks@user2772219n你选了哪一个?我先用我的解决方案试了一下。然后选择你的,因为它更简单,更短。