gpt4 book ai didi

javascript - 如何将所有文本包装到唯一的 span 标签中?

转载 作者:搜寻专家 更新时间:2023-11-01 04:58:00 25 4
gpt4 key购买 nike

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

包装前:

<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 中尝试过这个,但它没有给出我期望的结果

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

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

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

});

提前致谢,洛根

最佳答案

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

更新:这个版本不会悄悄地杀死空格 ;)

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

关于javascript - 如何将所有文本包装到唯一的 span 标签中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12105059/

25 4 0