【问题标题】:Append array to list items (one is to one pairing)将数组附加到列表项(一对一对)
【发布时间】:2013-09-17 17:39:53
【问题描述】:

我的列表目前的结构如下:

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

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

【问题讨论】:

    标签: jquery html append each


    【解决方案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

    您的代码的问题在于,在第一个 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]));
    });
    

    演示:Fiddle

    【讨论】:

    • 我会试试看效果如何。谢谢
    • @user2772219n 你选了哪一个
    • 我先用我的解决方案试了一下。然后选择你的,因为它更简单更短。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 2013-11-10
    • 2021-06-07
    相关资源
    最近更新 更多