开发者

Build Javascript Variable Using jquery Manipulation

开发者 https://www.devze.com 2022-12-19 16:48 出处:网络
I need to build a string variable using jQuery to find all the text nodes surrounded by span tags. Importantly I need to separate each segment of text with the pipe character \"|\".

I need to build a string variable using jQuery to find all the text nodes surrounded by span tags. Importantly I need to separate each segment of text with the pipe character "|".

For example take the following html:

<div id="myDiv">
<span>this</span> <span>is</span> <span>the</span> <span>text</span>
</div>

Using jQuery I need to produce the following:

var my_variable = "this|is|the|text";

So far I have the following jQuery statement but this just adds the pipe character at the end and doesn't separate each segment of text.

var my_variable = $("#myDiv").find("span").text() + '|';

Any help would be very much appreciated.

Note: To remove the last pipe character at the end of the string I was going to use:

my_n开发者_JAVA百科ew_variable = "my_variable.slice(0, -1)";


You can use map() on the element of spans to get the text. Javascript arrays have a join() method that will put the pipes between them but first you need to convert your jQuery object into a Javascript array. Use $.makeArray() for this.

var my_variable = $.makeArray($("#myDiv span").map(function() {
  return $(this).text();
})).join("|");


var strings = [];
$('#myDiv span').each(function(){
    strings.push($(this).text());
});
var my_variable = strings.join('|');


var pipeText="";

$('#myDiv span').each(function(){
  pipeText+=$(this).text() + "|";
});

pipeText = pipeText.slice(0, -1);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号