How to wrap all text into unique span tag?

后端 未结 2 1121
心在旅途
心在旅途 2021-01-03 07:37

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

Before wrap :

    

word word

2条回答
  •  日久生厌
    2021-01-03 08:06

    (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 $('', {id: count = count + 1, text: w}).get();
              }));
            }
          }
        });
      }('body'));
    }(0));
    

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

    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) : $('', {id: count = count + 1, text: w}).get();
            }));
          }
        });
      }('body'));
    }(0));
    

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

提交回复
热议问题