如何将所有文本包装成唯一的span标记? [英] How to wrap all text into unique span tag?

查看:77
本文介绍了如何将所有文本包装成唯一的span标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将所有正文(每个单词)包装成唯一的span标签。

I want to wrap all body text(each word) into unique span tag.

换行前

<body>    
<div>
  <p>word word </p>
  <div>word word</div>
    <ul>
        <li>word word</li>
    </ul>
  </ul>
  <p>word word <strong>word</strong> </p>
</div>
</body>

换行后

<body>
<div>
    <p><span id="1">word</span> <span id="2">word</span> </p>
    <div><span id="3">word</span> <span id="4">word</span></div>
    <ul>
        <li><span id="5">word</span> <span id="6">word</span></li>
    </ul>
    </ul>
    <p><span id="7">word</span> <span id="8">word</span> <strong><span id="9">word</span></strong> </p>
</div>
</body>

我在jquery中尝试了这个但它没有给出我期望的结果

I tried this in jquery but it doesn't give what i expect

$('body *').each(function(){

        var words = $(this).text().split(" ");

            $(this).empty();
            $t=$(this);
            $.each(words, function(i, v) {
                $t.append('<span>'+v+'</span>');
            });

});

提前致谢,
Logan

Thanks in advance, Logan

推荐答案

(function (count) {
  'use strict';
  (function wrap(el) {
    $(el).contents().each(function () {
      // Node.* won't work in IE < 9, use `1`
      if (this.nodeType === Node.ELEMENT_NODE) {
        wrap(this);
      // and `3` respectively
      } else if (this.nodeType === Node.TEXT_NODE) {
        var val = $.trim(this.nodeValue);
        if (val.length > 0) {
          $(this).replaceWith($.map(val.split(/\s+/), function (w) {
            return $('<span>', {id: count = count + 1, text: w}).get();
          }));
        }
      }
    });
  }('body'));
}(0));

http://jsfiddle.net/LNLvg/3/

更新:这个版本没有默默杀死whitspace;)

update: this version does not silently kill the whitspace ;)

(function (count) {
  'use strict';
  (function wrap(el) {
    $(el).filter(':not(script)').contents().each(function () {
      if (this.nodeType === Node.ELEMENT_NODE) {
        wrap(this);
      } else if (this.nodeType === Node.TEXT_NODE && !this.nodeValue.match(/^\s+$/m)) {
        $(this).replaceWith($.map(this.nodeValue.split(/(\S+)/), function (w) {
          return w.match(/^\s*$/) ? document.createTextNode(w) : $('<span>', {id: count = count + 1, text: w}).get();
        }));
      }
    });
  }('body'));
}(0));

http://jsfiddle.net/mtmqR/1/

这篇关于如何将所有文本包装成唯一的span标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆