2010-03-22 28 views
3

由於HTML以下塊:jQuery的 - 創建的列表中的所有LIS名稱的

<ul id="taglist"> 
<li><a name="45" href="">Product 1</a></li> 
<li><a name="1146" href="">Product 2</a></li> 
<li><a name="13437" href="">Product 3</a></li> 
<li><a name="51" href="">Product 4</a></li> 
</ul> 

是否有可能在jQuery來返回一個字符串,一個變量名爲值:

alert(tagliststring); 

將提醒:45,1146,13437,51

感謝

回答

7

可以使用each功能:

var names = []; 
$('#taglist > li > a').each(function() { 
    names.push(this.name); 
}); 
var result = names.join(','); 
alert(result); 

這樣,names將充滿每個人的名字的數組,result將是你正在尋找的逗號分隔的字符串。

欲瞭解更多信息,請參閱jQuery documentation

一個這樣做的更小的方法是使用jQuery的map功能:

var names = $('#taglist > li > a').map(function() { return this.name; }).get(); 
var result = names.join(','); 

第一個例子將可能會更容易爲人們閱讀和理解。

0
var output; 
$('li a').each(function() { output += $(this).attr('name') + ','; }); 

請注意,這將在最後輸出一個額外的,

+0

有沒有辦法讓它不在最後添加一個? – AnApprentice 2010-03-22 02:07:20

+0

參見@ TM的回答。 – 2010-03-22 02:09:18

5

使用$.map

var names = $('#taglist > li > a').map(function() { 
    return this.name; 
}).get().join(','); 
// names will contain the string: "45,1146,13437,51" 

$.map方法,可以通過函數在當前匹配的集合中的每個元件通過,產生含有的返回值的新jQuery對象。

$.map之後,我使用get方法獲得一個普通的JavaScript Array對象,我最終可以調用join方法來生成一個字符串。

檢查上述示例here

相關問題