gpt4 book ai didi

javascript - 在 html 内容之间插入标签

转载 作者:太空狗 更新时间:2023-10-29 13:05:46 25 4
gpt4 key购买 nike

我在 mydiv

中有以下示例内容
<div id="mydiv">
sample text sample text sample text...
......
<i>inner text </i> <i>sample text </i>
......
<b>sample text </b> <i>sample text </i>
</div>

现在我想在 mydiv 内容之间附加突出显示的 div。示例如下。

<div class="highlight">highlight text</div>

我想每 200 个单词插入这个 div,但问题是它不应该放在任何子标签中。例如,如果第 200 个单词是内部的,则不应像

<div id="mydiv">
sample text sample text sample text...
......
<i>inner<div class="highlight">highlight text</div> text </i> <i>sample text </i>
......
<b>sample text </b> <i>sample text </i>
</div>

它应该附加在内部标签之后

<div id="mydiv">
sample text sample text sample text...
......
<i>inner text </i> <div class="highlight">highlight text</div> <i>sample text </i>
......
<b>sample text </b> <i>sample text </i>
</div>

我尝试使用子字符串,但它位于子标签内。有什么办法可以做到这一点?我们可以使用任何 js 库。

最佳答案

执行此操作的最简单方法是遍历 div 的内容并将突出显示插入正确的位置。这是代码:

$(document).ready(function () {
// count of characters (modulo the period) and selected period
var count = 0, period = 200;

// iterator and highlight
var words = '', highlight = '<div class="highlight">highlight text</div>';

// loop through the contents
$('#mydiv').contents().each(function () {
// we only care about text contents
if (this.nodeType === 3) {
// get the individual words
words = $(this).text().split(' ');
// loop through them
for (var j = 0; j < words.length; j++) {
// increase count except if the word is empty (mutiple spaces)
if (words[j] && words[j] !== '\n') { count++; }
// if the period is exceeded, add the highlight and reset the count
if (count === period) {
words.splice(1 + j++, 0, highlight);
count = 0;
}
}
// replace the text
$(this).replaceWith(words.join(' '));
}
});
});

关于javascript - 在 html 内容之间插入标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41401645/

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