用jQuery把每个单词放在一个span中

时间:2013-10-16 17:48:36

标签: javascript jquery

我的文字看起来像这样 - >

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

有没有办法用jQuery将这些单词放在<span></span>标签中??

在互联网上似乎找不到这样的东西......

4 个答案:

答案 0 :(得分: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 Demo

答案 1 :(得分:0)

我相信你要找的是:

var myString = "car, building, money, computer, new phone, media chat, google plus, desk, gym";
var result = myString.split(', ');

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

答案 2 :(得分: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>'

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

答案 3 :(得分: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/