gpt4 book ai didi

javascript - 将多个
替换为一个

转载 作者:IT王子 更新时间:2023-10-29 02:59:14 29 4
gpt4 key购买 nike

我如何使用JavaScript来检测

<br>
<br>
<br>

成为一个

<br>

?

我试过:

jQuery('body').html().replace(/(\<br\>\r\n){3, }/g,"\n");

但这对我不起作用。

最佳答案

CSS 解决方案

如果要禁用多个<br>的效果在页面上,您可以通过 CSS 来完成,而无需使用 JavaScript:

br + br { display: none; }

但是,当您使用标签时,此方法非常理想,如下所示:

<div>Text</div><br /><br /><br />
<div>Text</div><br /><br /><br />
<div>Text</div><br /><br /><br />

在其他情况下,像这样:

Hello World<br />   <br />
Hello World<br /> <br />
Hello World<br /> <br />

它会失败(因为 CSS 传递文本节点)。相反,请使用 JavaScript 解决方案。


JavaScript 解决方案

// It's better to wait for document ready instead of window.onload().
window.onload = function () {
// Get all `br` tags, defined needed variables
var br = document.getElementsByTagName('br'),
l = br.length,
i = 0,
nextelem, elemname, include;

// Loop through tags
for (i; i < l - 1; i++) {
// This flag indentify we should hide the next element or not
include = false;

// Getting next element
nextelem = br[i].nextSibling;

// Getting element name
elemname = nextelem.nodeName.toLowerCase();

// If element name is `br`, set the flag as true.
if (elemname == 'br') {
include = true;
}

// If element name is `#text`, we face text node
else if (elemname == '#text') {
// If text node is only white space, we must pass it.
// This is because of something like this: `<br /> <br />`
if (! nextelem.data.replace(/\s+/g, '').length) {
nextelem = br[i+1];
include = true;
}
}

// If the element is flagged as true, hide it
if (include) {
nextelem.style.display = 'none';
}
}
};

关于javascript - 将多个 <br> 替换为一个 <br>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17061931/

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