2011-02-25 75 views
8

I:jQuery的內爆/與自定義字符加入字符串(元素)(連字符)

$(this).parents("tr:first").children("td").children("span"); 

當我做到這一點:

$(this).parents("tr:first").children("td").children("span").text(); 

跨度中的文本(比如a和b)連接在一起(ab),這就是我想要的

但是現在我想通過在中間插入連字符( - b) 我已經嘗試這樣做,但是,這並不工作:

$(this).parents("tr:first").children("td").children("span").join(" - "); 
+1

加入用於與陣列elements.you不能直接與一個變量使用它。 – Vivek 2011-02-25 12:05:08

+0

ah,+1 ......... – Michel 2011-02-25 15:19:49

回答

17

使用$ .MAP:

$.map(
    $(this).parents("tr:first").children("td").children("span"), 
    function(element) { 
     return $(element).text() 
    }) 
    .join(" - "); 
+4

或這種結構:'$(this).parents(「tr:first」)。children(「td」)。children(「span」)。map(函數(i,element){return $(element).text()})。get()。join(「 - 」)' – aavezel 2011-02-25 12:11:50

+0

是啊!工作。不知道'地圖',現在就查找它。 – Michel 2011-02-25 15:19:27

5

也許這樣的事情...

var m = []; 
$(this).parents("tr:first").children("td").children("span").each(function(index, element) {m.push(element.text());}); 
return m.join(" - "); 
1

你可以試試這個可能會覺得有點沉重不那麼複雜。

$(this).parents("tr:first td span:eq(0)").text() + " - " + $(this).parents("tr:first td span:eq(1)").text() 
0
$(this) 
    .parents('tr:first') 
    .children('td') 
    .children('span') 
    .append('-') // append hyphen to each span 
    .text();