-2

I have a text that looks like this ->

car, building, money, computer, new phone, media chat, google plus, desk, gym

Is there a way of putting each of these words in a <span></span> tag with jQuery..?

Can't seem to find something like this in internet...

4

4 回答 4

3

从您的字符串中,您可能希望首先将其拆分为逗号并创建一个数组:

var sentence = "car, building, money";
var words = sentence.split(',');

然后我们需要一个跨度的目的地:

var $container = $('#container'); // something in your UI, a div maybe

然后您可以将每个包装在一个跨度中并将其添加到容器中:

$.each(words, function() {
     // create a span whose content is the result of trimming
     // the current array item
     $container.append($('<span>').html($.trim(this)));
});

jsFiddle 演示

于 2013-10-16T17:51:08.057 回答
0

我相信您正在寻找的是:

var myString = "汽车、建筑、金钱、电脑、新手机、媒体聊天、google plus、办公桌、健身房";
var 结果 = myString.split(', ');

result现在引用字符串中所有名称的数组。您可以遍历数组并动态创建 html 标记并将值放入其中。

于 2013-10-16T17:55:01.153 回答
0
var str = 'car, building, money, computer, new phone, media chat, google plus, desk, gym'
'<span>'+str.replace(/, /g,"</span><span>")+'</span>'

或者

'<span>'+str.replace(/, /g,"</span>, <span>")+'</span>'

取决于你想要达到的结果(你不太擅长制定任务)

于 2013-10-16T17:56:35.473 回答
0

尝试以下:

   var string1 = "car, building, money, computer, new phone, media chat, google plus, desk, gym";
    var str = string1.split(",");
    var container = jQuery('<div>');
    jQuery.each(str,function(k,v){
        container.append(jQuery('<span>').html(v));
    });
    console.log(container);

这是演示:http: //jsfiddle.net/dCYyY/

于 2013-10-16T17:57:03.280 回答