gpt4 book ai didi

javascript - 如何在文本编辑器中换行(跨度)单词

转载 作者:行者123 更新时间:2023-11-28 04:49:26 27 4
gpt4 key购买 nike

我有一个像这样的 JavaScript 变量:

var text = "A <mark id='1'>businessman</mark> should be able to <mark id='1'>manage</mark> his business matters";

我想将每个单词包装在具有不同 id 的 span 元素中,但保留已包装在 <mark> 中的单词。标签。像这样:

text = "<span id='1'>A </span><mark id='1'>businessman</mark><span id='2'>should</span><span id='3'>be </span><span id='4'>able </span><span id='5'>to </span><mark id='2'>manage</mark><span id='6'>his </span><span id='7'>business </span><span id='8'>matters</span>";

我想要用 javascript 或 jquery 实现所有这些,但无法得到它。如果你们能帮助我,那就太好了。

谢谢。

最佳答案

试试这个,

function removeEmptyStrings(k) {
return k !== '';
}

function getWordsArray(div) {
var rWordBoundary = /[\s\n\t]+/; // split by tab, newline, spaces
var output = [];
for (var i = 0; i < div.childNodes.length; ++i) { // Iterate through all nodes
var node = div.childNodes[i];
if (node.nodeType === Node.TEXT_NODE) { // The child is a text node
var words = node.nodeValue.split(rWordBoundary).filter(removeEmptyStrings); // check for emptyness
for (var j = 0, l = words.length; j < l; j++) {
// adding class txtSpan so that it will not affect your spans already available in your input.
output.push('<span class="txtSpan">' + words[j] + '</span>');
}
} else { // add directly if not a text node
output.push(node.outerHTML);
}
}
return output;
}
var counter = 1,
html = getWordsArray($('#editor')[0]).join('');
$('#output').html(html).find('span.txtSpan').each(function() {
this.id = 'span-' + counter++;
});
span.txtSpan {
padding: 2px;
display: inline-block;
text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="editor">
A <mark id='1'>businessman</mark> should be able to <mark id='1'>manage</mark> his business matters
</div>
<div id="output">

</div>

关于javascript - 如何在文本编辑器中换行(跨度)单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43063416/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com