将数组追加到列表项(一个是一个配对)

时间:2013-09-13 06:15:28

标签: 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)
      </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>

我想在锚标记之后得到括号内的数字。所以我这样做了:

jQuery('#list-items li').each(function() {
     b = jQuery(this).first().contents().filter(function() {
        return this.nodeType == 3;
        }).text();
});

对于我的上一个任务,我需要将上述输出附加到每个列表项的锚标记。所以我尝试了这个:

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]);
});

这似乎不起作用。我不知道为什么..任何人都可以帮我修改我的剧本?感谢。

1 个答案:

答案 0 :(得分:1)

一个简单的解决方案

jQuery('#list-items li > a').append(function() {
    var next = this.nextSibling;
    if(next){
        return $.trim($(next).text())
    }
});

演示:Fiddle

如果您想创建数组b,我建议使用.map()代替.each()

var b = jQuery('#list-items li a').map(function() {
    var next = this.nextSibling;
    if(next){
        return $.trim($(next).text())
    }
});

jQuery('#list-items li a').append(function(i) {
    jQuery(this).append(b[i]);
});

演示:Fiddle

您的代码的问题是,在第一个循环中,您覆盖了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]));
});

演示:Fiddle

相关问题