我正在从以下几个元素中收集文本:-
I am collecting the text from several elements like this:-
$('#element').find('p').text();但是,这将返回所有加在一起的'p'元素的文本,而没有任何形式的定界.例如如果每个"p"元素都包含一个音乐家/艺术家的名字,那么在收集所有这些元素时都会得到以下信息:-
However this returns the text of all the 'p' elements added together without any form of delimiting. e.g. If each 'p' element contains a musician/artist name I get the following when collecting them all:-
The BeatlesRadioheadBritney Spears
The BeatlesRadioheadBritney Spears
我想做的是在每个艺术家之间插入一个空格(或逗号),以便上面的列表看起来像:-
What I want to do is insert a space (or comma) between each artist so that the above list looks like:-
甲壳虫乐队Radiohead布兰妮·斯皮尔斯
The Beatles Radiohead Britney Spears
我可以想象.map/.split/.join函数可以解决这个问题,但是我对jQuery的缺乏经验使我回到了这里.
I would imagine the .map/.split/.join function will do the trick but my inexperience with jQuery is holding me back here.
有什么想法吗?
推荐答案您正确地将.map与.join一起使用.
You are right about using .map along with .join.
尝试这样的事情:
var names = $('#element').find('p').map(function(){ return $(this).text(); }).get().join(','); console.log(names); //The Beatles,Radiohead,Britney Spears更多推荐
用jQuery分隔文本字符串
发布评论