2010-12-02 15 views
7

我需要在一個div所有跨度值讀取到數組或字符串需要將div中的所有span值作爲數組或字符串?

 
var tag_text_arr=$("#div_id span").each(function(){ 
     return $(this).text(); 
    }); 

其實我需要獲取裏面的div所有跨度值,並希望創建這樣

span1_val串| span2_val | span3_val | span4_val

如果這是可能的解釋我...

+1

什麼是你想完成你需要他們在用'分隔字符串'|' – Webnet 2010-12-02 16:32:13

回答

13

這應該輸出你需要的字符串:

var arr = []; 
$("#div_id span").each(function(index, elem){ 
    arr.push("span" +index+ "_" + $(this).text()); 
}); 
return arr.join("|"); 

工作演示:http://jsfiddle.net/HmUUB/

這將開始編號在span0,而不是span1。如果您想要它從span1開始,請使用+(index + 1)+而不是+index+(example)


如果我讀了你的問題錯了(你不想 spann_前綴的每個元素在字符串中,你可以使用jQuery的 $.map()功能:

var tag_text_arr = $.map($("#div_id span"), function(elem, index){ 
    return $(elem).text(); 
}).join("|"); 

return tag_text_arr; 

工作演示:http://jsfiddle.net/BQLj6/

0
final val; 

var tag_text_arr=$("#div_id span").each(function(){ 
     val=val+ $(this).text() + "|"; 
    }); 

alert(val.substring(0,val.length-1)); 

這應該做

+0

@mohan RAM,我給像一個僞代碼,你可以完善它furthur ... – kobe 2010-12-02 16:34:39

0

你已經完成了大部分工作。你可以使用

A.將$(this).text()的輸出附加到一個數組,並用管道將.join()數組附加到數組。B.連接$(this).text()將一個管道符號輸出到一個字符串,然後在循環後刪除最後一個管道。

0

你幾乎沒有...

var span_text = ""; 
$("#div_id span").each(function() { 
    span_text += $(this).text() + "|"; 
}); 
var span_text.substring(0, span_text.length - 1); // remove the trailing | character. 
0

像這樣的東西應該做的伎倆:

var result = $('#div_id').find('span').map(function(i,e){ 
    return $(e).text(); 
}) 
.get()  // Stop here for an array 
.join('|'); // or here for a string 
1
var spanValues = []; 
var tag_text_arr=$("#div_id span").each(function(){ 
    spanValues.push($(this).text()); 
}); 
var pipedSpanValues = spanValues.join("|"); 
2

使用jQuery map方法可以返回所需文本的數組,然後使用join來連接它們。

var x = $.map($("span"), function(item) { 
    return $(item).text(); 
}).join("|"); 

alert(x); 

的jsfiddle這裏:http://jsfiddle.net/Ewdge/

相關問題