0

我目前有一个动态拉入页面的品牌名称列表,需要根据其品牌名称在 4 个列表之间进行分段。例如,一列将包含以数字开头的任何内容。第二列将包含所有以字母 A 到 H 开头的品牌。第三列 IP。第四栏QZ。我目前正在尝试使用 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>

4

1 回答 1

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/


如果你想让代码稍微一点,你可以将正则表达式存储在一个 map 对象中:

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/

于 2013-08-01T00:58:00.303 回答