[翻译]  Add html tags to every letter in a string

[CHINESE]  将html标记添加到字符串中的每个字母


I have a string of letters within a div - such as this...

我在div中有一串字母 - 比如这......

<div>hello</div>

I'd like to add a html tag to each letter in the string so it will be - such as this

我想为字符串中的每个字母添加一个html标记,这样就可以了 - 就像这样

<div>
    <span>h</span>
    <span>e</span>
    <span>l</span>
    <span>l</span>
    <span>o</span>
</div>

Since the letters within this div will be dynamically changing it can't be static thus I'd like to use jquery to apply spans to every letter of the string.

由于此div中的字母将动态更改,因此它不能是静态的,因此我想使用jquery将spans应用于字符串的每个字母。

Any help would be appreciated - thanks!

任何帮助将不胜感激 - 谢谢!

7 个解决方案

#1


5  

A few steps:

几个步骤:

  1. Grab the text contents and create an array of individual characters,
  2. 抓取文本内容并创建一个单独的字符数组,
  3. Empty the original container,
  4. 清空原始容器,
  5. Add each letter as a span element.
  6. 将每个字母添加为span元素。

The code:

代码:

$('div').each(function() {
    var letters = $(this).text().split(''),
    $container = $(this).empty();

    $.each(letters, function(_, letter) {
       $('<span>', {text: letter}).appendTo($container);
    });
});

Demo

演示

#2


3  

You can just split the textContent then join it up again with suitable markup embedded. So presuming you have a reference to the div:

您可以拆分textContent,然后使用嵌入的合适标记再次将其连接起来。所以假设你有一个div的引用:

div.innerHTML = '<span>' + (div.textContent || div.innerText).split('').join('<\/span><span>') + '<\/span>';

Edit

There's always one kill–joy who points out the obvious flaw!! Ok, here's something more robust.

总有一个杀戮喜悦指出明显的缺陷!!好的,这里有更强大的东西。

function spanizeText(element) {
  var text = (element.textContent || element.innerText).split('');
  element.innerHTML = '';

  text.forEach(function(c) {
    var sp = document.createElement('span');
    sp.appendChild(document.createTextNode(c));
    element.appendChild(sp);
  });
}

It requires a polyfil for forEach in old browsers, or change forEach to a plain for loop (same number of lines of code, probably runs faster). It could be modified to accept a wrapper element that was setup with various attributes and properties that is cloned rather than use document.createElement.

它在旧浏览器中需要forFach的polyfil,或者将forEach更改为plain for循环(相同数量的代码行,可能运行得更快)。可以修改它以接受使用克隆的各种属性和属性设置的包装元素,而不是使用document.createElement。

#3


2  

HTML Code

HTML代码

<div id="str">hello</div>
<div id="result">

</div>

JS Code

JS代码

$(function(){
    var str= $('div#str').html();
    for(var i=0; i<str.length; i++){
        $('div#result').append('<span>'+str[i]+'</span>');
    }
});

#4


2  

Try,

尝试,

var xDiv = $('div');
var xChars = $.trim(xDiv.text()).split('');
xDiv.empty();

$.each(xChars,function(i,val){
  xDiv.append($('<span>'+ val +'</span>'));
});

#5


1  

You could also do this with a regex:

您也可以使用正则表达式执行此操作:

//var s = 'hello';
var s = $('#myDiv').html(); // get the string from the div

var newStr = s.replace(/(.)/gi, function(str, g1) {
    return '<span>' + g1 + '</span>';
});

alert(newStr);

#6


1  

Here is a JSfiddle demoing one way to do this.

这是一个JSfiddle演示一种方法来做到这一点。

  1. Select text
  2. 选择文字
  3. Split text into an Array of letters
  4. 将文本拆分为一个字母数组
  5. Iterate over the Array and append to target element
  6. 迭代数组并附加到目标元素

Jquery

jQuery的

// For all matching elements
$(string).each(function() {

    // Get contents of string
    var myStr = $(this).html();

    // Split myStr into an array of characters
    myStr = myStr.split("");

    // Append strings to the result div in spans
    for (var i = 0, len = myStr.length; i < len; i++) {
        $("#result").append("<span>"  + myStr[i] + "</span>");
    }
});

Html output

Html输出

<div id="letters">hello world</div>

<div id="result">
  <span>h</span>
  <span>e</span>
  <span>l</span>
  <span>l</span>
  <span>o</span>
  <span> </span>
  <span>w</span>
  <span>o</span>
  <span>r</span>
  <span>l</span>
  <span>d</span>
</div>

#7


1  

var txt = $("div").text();
var html = [];
for(var i in txt) html.push("<span>" + txt[i] + "</span>");
$("div").html(html.join(""));

I wouldn't use html() or append() with every character. This will force the browser to re-calc with every call. It's better to build your content and update when ready.

我不会对每个字符使用html()或append()。这将强制浏览器在每次调用时重新计算。最好是在准备好后构建内容并进行更新。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号