如何根据其内容在四个其他无序列表中的无序列表<ul>中追加列表项<li> </ul> </li>

时间:2013-08-01 00:48:59

标签: javascript jquery

我目前有一个动态拉入页面的品牌名单,需要根据品牌名称在4个列表之间进行细分。例如,一列将保存以数字开头的任何内容。第二列将保留所有以字母A至H开头的品牌。第三列I-P。第四栏Q-Z。我目前正在尝试使用jquery中的.map()函数来遍历列表并将项目拉出并附加到相应的列表但是有一些困难。任何帮助将不胜感激!

(注意:不是实际的品牌列表......最终名单中将有大约50个品牌。)

这是我的HTML:

<div class="brand-directory-body">
  <ul class="brand-directory-list" style="display:none;">
     <li class="brand">37 Signals</li>
     <li class="brand">Apple</li>
     <li class="brand">BMG</li>
     <li class="brand">Cartoon Network</li>
     <li class="brand">Disney</li>
     <li class="brand">ENews</li>
     <li class="brand">Nike</li>
     <li class="brand">Adidas</li>
     <li class="brand">Frito</li>
     <li class="brand">Coke</li>
     <li class="brand">Adobe</li>
     <li class="brand">Hostess</li>
     <li class="brand">Dominoes Pizza</li>
     <li class="brand">Honest Co</li>
     <li class="brand">Z Brand</li>
</ul>
<div class="brand-directory-column">
     <h3 class="column-title">#</h3>
     <ul class="brand-directory-list-num"></ul>
</div>
<div class="brand-directory-column">
     <h3 class="column-title">A-H</h3>
     <ul class="brand-directory-list-ah"></ul>
</div>
<div class="brand-directory-column">
     <h3 class="column-title">I-P</h3>
     <ul class="brand-directory-list-ip"></ul>
</div>
<div class="brand-directory-column">
     <h3 class="column-title">Q-Z</h3>
     <ul class="brand-directory-list-qz"></ul>
</div>

1 个答案:

答案 0 :(得分:4)

var lists = {
    numbers: [],
    AH: [],
    IP: [],
    QZ: []
};

$('.brand').each(function () {
    var letter = $.text(this).substr(0, 1);

    if ( /\d/.test(letter) ) {
        lists.numbers.push(this);
    }
    else if ( /[a-h]/i.test(letter) ) {
        lists.AH.push(this);
    }
    else if ( /[i-p]/i.test(letter) ) {
        lists.IP.push(this);
    }
    else if ( /[q-z]/i.test(letter) ) {
        lists.QZ.push(this);
    }
});

$('.brand-directory-list-num').append( lists.numbers );
$('.brand-directory-list-ah').append( lists.AH );
$('.brand-directory-list-ip').append( lists.IP );
$('.brand-directory-list-qz').append( lists.QZ );

这是小提琴:http://jsfiddle.net/q697n/


如果你想让代码变得有点DRY,你可以将正则表达式存储在地图对象中:

var lists = {
    numbers: [],
    AH: [],
    IP: [],
    QZ: []
};

var map = {
    numbers: /\d/,
    AH: /[a-h]/i,
    IP: /[i-p]/i,
    QZ: /[q-z]/i
}

$('.brand').each(function () {

    var el = this, letter = $.text(this).substr(0, 1);

    $.each(map, function (key, regex) {
        if ( regex.test(letter) ) {
            lists[key].push(el);
            return false;
        }
    });
});

$('.brand-directory-list-num').append( lists.numbers );
$('.brand-directory-list-ah').append( lists.AH );
$('.brand-directory-list-ip').append( lists.IP );
$('.brand-directory-list-qz').append( lists.QZ );

这是小提琴:http://jsfiddle.net/q697n/1/