用逗号/空格将分隔的名称插入通过jQuery创建的<li> </li>

时间:2011-07-11 21:41:20

标签: jquery html-lists space comma

我有几个以逗号分隔的演员名字,我试图获取该列表中的每个名称并将其插入到ul下自己动态创建的li中,同时仅将首字母大写并修剪逗号/空格(唯一不应修剪的空间是“john lock”,因为名称之间没有逗号),如下所示:

var cast = ('jack, kate ,sawyer , john lock ,, hurley')

<ul id="cast-members">
<li>Jack</li>
<li>Kate</li>
<li>Sawyer</li>
<li>John Lock</li>
<li>Hurley</li>
</ul>

知道如何使用jQuery实现这一目标吗?

1 个答案:

答案 0 :(得分:1)

这应该这样做

var cast = 'jack, kate ,sawyer , john lock ,, hurley';
var castlist = cast.split(',');

var $ul = $('<ul>'); //create an in-memory <ul> element to hold our elements

$.each(castlist, function(idx,val){ // for each item in the split array
    var value = $.trim(val).replace(/\b\S/g, function(m){return m.toUpperCase();}); // trim and capitalize the item
    if (value.length > 0){ // if its length > 0 (non-empty)
        var $li = $('<li>', { // create a <li> element
            html: $('<a>', { // set its html to be a new <a> element
                href:'Bio.html#'+value, // with a href
                text:value // and a text value
            })
        });
        $ul.append($li); // append our new <li> to the <ul>
    }
});
$('.lost-cast').append( $ul );  // append the filled <ul> in the /lost-cast element 

演示http://jsfiddle.net/gaby/gvb6n/