jQuery - 如何在跨度中包装字符串中的每个字符

时间:2016-12-13 07:06:20

标签: javascript jquery

如何将div的字符转换为span?

例如,我想转换一下:

<div>
    Hello World
</div>

进入这个:

<div>
    <span>H</span>
    <span>e</span>
    <span>l</span>
    <span>l</span>
    <span>o</span>
    <span>W</span>
    <span>o</span>
    <span>r</span>
    <span>l</span>
    <span>d</span>
</div>

我尝试了this StackOverflow suggestion,但是将空格转换为跨度。我需要的是只将字符转换为跨度:

$("div").each(function (index) {
    var characters = $(this).text().split("");

    $this = $(this);
    $this.empty();
    $.each(characters, function (i, el) {
        $this.append("<span>" + el + "</span");
    });
 });

7 个答案:

答案 0 :(得分:2)

您可以使用html()方法和{{3}}方法进行回调来减少代码。

$("div").html(function(index, html) {
  return html.replace(/\S/g, '<span>$&</span>');
});

$("div").html(function(index, html) {
  return html.replace(/\S/g, '<span>$&</span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  Hello World
</div>

答案 1 :(得分:2)

您可以尝试使用这个简单的 JavaScript

(function() {
  var div, i, span = "";
  div = document.querySelectorAll("div")[0];
  for (i = 0; i < div.innerText.length; i++) {
    if (div.innerText[i] !== " ") {
      span += "<span>";
      span += div.innerText[i];
      span += "</span>";
    }
  }
  div.innerHTML = span;
})();
<div>
  Hello World
</div>

答案 2 :(得分:1)

我更喜欢使用正则表达式:

&#13;
&#13;
var txt = $('#container').text();
var newTxt = txt.replace(/\w/g,function(c){
  return '<span>'+c+'</span>';
})
$('#container').html(newTxt);
&#13;
span {
  display:inline-block;
  background-color:#dfdfdf;
  color:#aaa;
  padding:3px;
  margin:3px;
  border-radius:3px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
    Hello World
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

var textWrapper = document.querySelector('h1');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");
<h1>Hello world</h1>

答案 4 :(得分:0)

$("div").each(function (index) {
var characters = $(this).text().split("");

$this = $(this);
$this.empty();
$.each(characters, function (i, el) {
if(el != ' ')
$this.append("<span>" + el + "</span");
});

为空间设置条件

答案 5 :(得分:0)

尝试:

$("div").each(function (index) {
  var characters = $(this).text().split("");
  characters = characters.filter(v => v != '');
  $(this).empty();
  for(var i =0; i < characters.length; i++) {
      $(this).append("<span>" + characters[i] + "</span");
  }    
});

答案 6 :(得分:0)

尝试尽可能少地写

HTML

<div>
    HelloWorld
</div>

JS

var d=$("div");
var text=d.text();
text=$.trim(text);
d.empty();

for(i=0;i<text.length;i++){
    var span=$("<span></span>");
    span.text(text[i]);
    d.append(span)
}