将每个字母放在给定div中的单独范围内

时间:2014-05-09 12:54:29

标签: javascript jquery html

以下div包含一些文字和标签。我想将<span>标记添加到div中的每个字母。

<div id="text">Hello, <span class="name">John</span></div>

我需要输出如下:

<div id="text">
  <span>H</span>
  <span>e</span>
  <span>l</span>
  <span>l</span>
  <span>o</span>
  <span>,</span>
  <span class="name">J</span>
  <span class="name">o</span>
  <span class="name">h</span>
  <span class="name">n</span>
</div>

<div id="text">
  <span>H</span>
  <span>e</span>
  <span>l</span>
  <span>l</span>
  <span>o</span>
  <span>,</span>
  <span class="name">
     <span>J</span>
     <span>o</span>
     <span>h</span>
     <span>n</span>
  </span>
</div>

大多数人的答复说我没有尝试任何东西。对于所有人,如果代码中不存在dos,我会有解决方案。在发布问题之前,我已经完成了以下操作。

<div id="text">Hello, John</div>

答案:

<div id="text">
  <span>H</span>
  <span>e</span>
  <span>l</span>
  <span>l</span>
  <span>o</span>
  <span>,</span>
  <span>J</span>
  <span>o</span>
  <span>h</span>
  <span>n</span>
</div>

使用的Javascript:

var obj=$('#text');
var text=obj.text();
text=text.split("");
var parsed="";
obj.empty();
for(var i=0; i<text.length; i++)
{
var tag=document.createElement('span');
tag.setAttribute('class','vtag');
tag.innerHTML=text[i];
obj.append(tag);
}

3 个答案:

答案 0 :(得分:3)

我(最近)一直在你的鞋子里,甚至不知道从哪里开始。魔术词是&#34; JavaScript DOM操作&#34;:

var text = document.getElementById("text");
var string = "Hello, John";
string.split("");
var i = 0, length = string.length;
for (i; i < length; i++) {
    text.innerHTML += "<span>" + string[i] + "</span>";
}

这只是让他们全部跨越。您应该尝试尝试让<span class="name">位从此处自行运行。

答案 1 :(得分:2)

您可以尝试这样的事情:http://jqversion.com/#!/LKQqeGh(使用jQuery)

var $div = $('#text').clone().html('');
$('#text').contents().each(function(){
  var spanClass = '';

  if ($(this).is('span')) {
    spanClass = $(this).attr('class');
  }

  $textArray = $(this).text().split('');

  for (var i = 0; i < $textArray.length; i++) {
    $('<span>').addClass(spanClass).text($textArray[i]).appendTo($div);
  }
});

$('#text').replaceWith($div);

答案 2 :(得分:2)

HTML:

<div id="text">Hello, <span class="name">John</span></div>

Pure Javascript:

var text = document.getElementById("text");
var msg = text.textContent;
var name = document.getElementsByClassName("name")[0].textContent;

// remove name from msg
msg = msg.substring(0,msg.length - name.length);
// to char array
msg = msg.split('');
name = name.split('');

text.innerHTML = "<span>" + msg.join("</span><span>") + "</span>";
text.innerHTML += "<span class=\"name\">" + name.join("</span><span class=\"name\">") + "</span>";

演示JSFiddle