我有几个用逗号分隔的角色名称,我正在尝试获取该列表中的每个名称,并将其插入到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实现这一点吗?
发布于 2011-07-12 05:47:42
这应该就行了
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/上演示
https://stackoverflow.com/questions/6656977
复制相似问题