如何将所有文本包装成唯一的span标签?

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

换行前

 

word word

word word
  • word word

word word word

包裹后

  

word word

word word
  • word word

word word word

我在jquery中尝试了这个但是它没有给出我期望的东西

 $('body *').each(function(){ var words = $(this).text().split(" "); $(this).empty(); $t=$(this); $.each(words, function(i, v) { $t.append(''+v+''); }); }); 

洛根,提前谢谢

 (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/

更新 :此版本不会以静默方式终止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/

这是一个使用普通javascript的解决方案,它包含跨越的单词并保留文本中的空格,但将它们留在跨度之外,因此只有单词本身在跨度中:

 function splitWords(top) { var node = top.firstChild, words, newNode, idCntr = 1, skipChild; var re = /\S/; while(node && node != top) { skipChild = false; // if text node, check for our text if (node.nodeType == 3) { if (re.test(node.nodeValue)) { newNode = null; words = node.nodeValue.split(" "); for (var i = 0; i < words.length; i++) { if (words[i] === "") { newNode = document.createTextNode(" "); node.parentNode.insertBefore(newNode, node); } else { newNode = document.createElement("span"); newNode.id = "word" + idCntr++; newNode.innerHTML = words[i]; node.parentNode.insertBefore(newNode, node); if (i < words.length - 1) { newNode = document.createTextNode(" "); node.parentNode.insertBefore(newNode, node); } } } if (newNode) { node.parentNode.removeChild(node); node = newNode; // don't go into the children of this node skipChild = true; } } } else if (node.nodeType == 1) { if (node.tagName == "SCRIPT") { skipChild = true; } } if (!skipChild && node.firstChild) { // if it has a child node, traverse down into children node = node.firstChild; } else if (node.nextSibling) { // if it has a sibling, go to the next sibling node = node.nextSibling; } else { // go up the parent chain until we find a parent that has a nextSibling // so we can keep going while ((node = node.parentNode) != top) { if (node.nextSibling) { node = node.nextSibling; break; } } } } } 

一个工作演示: http : //jsfiddle.net/jfriend00/3mms7/

仅供参考,我将id值设为“word1”,“word2”等...因为在HTML5之前,id值不允许以数字开头。