使用jQuery如何将文本拆分为span数组

时间:2015-02-03 04:56:33

标签: jquery

我想分割文字以使用html <span>

来控制它

这是我的HTML代码

<div class="siteLabel">Gallery/Technology/Music/Video/Business/Nature/People/Sports/Car/Fashion/Learn/Typography</div>

结果应该是这样的

<div class="siteLabel">
  <span>Gallery</span>
  <span>Technology</span>
  <span>Music</span>
  <span>Video</span>
  <span>Business</span>
  <span>Nature</span>
  <span>People</span>
  <span>Sports</span>
  <span>Car</span>
  <span>Fashion</span>
  <span>Learn</span>
  <span>Typography</span>
</div>

问题是标签编号不是静态的,可能更多或更少,所以我不能使用.split('/')

之类的东西

5 个答案:

答案 0 :(得分:3)

var arr = $(".siteLabel").text().split("/");
var html="";
for (i = 0; i < arr.length; ++i) {
    html+= "<span>"+arr[i]+"</span>";
}
$(".siteLabel").html(html);

<强> Demo

答案 1 :(得分:1)

我的偏好是仍然使用.split('/')。以下是使用纯JavaScript的方法:

var el = document.querySelector('.siteLabel');
var text = el.textContent ? el.textContent : el.innerText;
var items = text.split('/');
var html = '';

items.forEach(function(text){  
  html += '<span>'+text+'</span>';
});

el.innerHTML = html;

演示:http://jsfiddle.net/e97e4Lsd/2/

答案 2 :(得分:1)

您可以使用像

这样的简单正则表达式

$('.siteLabel').html(function(i, html) {
  return html.trim().replace(/(.+?)(\/|$)/g, '<span>$1</span>')
})
.siteLabel span {
  margin-right: 5px;
  border: 1px solid grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="siteLabel">Gallery/Technology/Music/Video/Business/Nature/People/Sports/Car/Fashion/Learn/Typography</div>

答案 3 :(得分:1)

尝试

$(".siteLabel").html(function(_, words) {
  return words.match(/[^\/]\w+/g).map(function(word) {
           return $("<span>", {"html": word}).add("<br />")
         });
})

$(".siteLabel").html(function(_, words) {
  return words.match(/[^\/]\w+/g)
            .map(function(word) {
              return $("<span>", {"html": word}).add("<br />")
            });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <div class="siteLabel">Gallery/Technology/Music/Video/Business/Nature/People/Sports/Car/Fashion/Learn/Typography</div>

答案 4 :(得分:0)

var items = $('.siteLabel').text().split('/');
    debugger;
$('.siteLabel').empty();
$.each(items, function(index, item){
    debugger;
    $('.siteLabel').append("<span>" + item)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>