2015-04-21 27 views
0

什麼是jQuery來串聯,以達到最佳的方式 「carid1 | engineid1,carid2 | engineid2」,例如: 「244 | 504442 | 882」jQuery的構建CSV字符串變量中串聯

$('#tblResults input[id*="ShowRoom"]').each(function(i, item){ 
strValue = $(this).attr("carid") + '|' + $(this).attr("engineid"); 

alert(strValue); 

}).get().join(","); 

下面是HTML

<TABLE width="100%" class="normal" id="tblResults" border="0" cellSpacing="0" cellPadding="0"> 
    <TBODY> 
    <TR class=header> 
    <TH class=sortLPad title="Sort by URN" onclick="reSort('0')" align=left>URN </TH> 

    <TH class=sortLPad title="Sort by ShowRoom" onclick="reSort('5')" align=left>Show Room</TH></TR> 

    <P></P> 

    <TR EventId="504"> 
    <TD id=URN noWrap>23KV9878788</TD> 

    <TD id="ShowRoom" class=lPad><INPUT onfocusin=clearField(this); id="ShowRoom0" onfocusout=resetField(this); onkeypress=validate(this) maxLength=1 value=1 size=1 version="2000120420142859" elementname="ShowRoom" engineid="504" carid="244"></TD> 

    </TR> 

    <TR EventId="403"> 
    <TD id=URN noWrap>889878744</TD> 

    <TD id="ShowRoom" class=lPad><INPUT onfocusin=clearField(this); id="ShowRoom2" onfocusout=resetField(this); onkeypress=validate(this) maxLength=1 value=1 size=1 version="2000120420142859" elementname="ShowRoom" engineid="882" carid="442"></TD> 

    </TR> 

    </TBODY> 
</TABLE> 

回答

0

您當前.each方法返回你迭代每個input元素;因此.get().join(',')將不起作用。而是將值推入一個數組,然後使用join(',')進行連接。

var arr = []; 
$('#tblResults input[id*="ShowRoom"]').each(function(i, item){ 
strValue = $(this).attr("carid") + '|' + $(this).attr("engineid"); 
    arr.push (strValue) 
}); 

console.log (arr.join (',')) // returns 244|504,442|882 
+1

@Regent它不是關於性能。上面的OP發佈的代碼不能按縮進工作。所以我已經向他展示瞭如何這樣做。順便說一句:如果性能優先,我甚至不會使用'jQuery' – Praveen

+0

[更簡單](http://jsperf.com/jquery-element-each-vs-simple-for/2) – Praveen

+0

@Regent:我是新的到JavaScript和jQuery。 jquery是不是隻是用來優化編碼?我感到震驚jquery是如此廣泛流行的性能問題:( – Gauls