我需要在包含文本节点的页面代码中将直接的 html 兄弟合并为一个。
<div>some text
<b>some text</b> som
e text <b>text</b><b> more text</b> some te
xt</div>
这是使用 rangy 和 jQuery 编辑代码后的实际输出,我需要在编辑后清除它,所以它看起来像这样:
<div>some text <b>some text</b> some text <b>text more text</b> some text</div>
我想用 jQuery 来做这件事。我知道函数 unwrap() 和 wrapAll() 但我不能有效地组合它们。 感谢您提供任何线索或帮助!
最佳答案
您需要一个一个地遍历子节点;将节点与前一个节点进行比较,并在必要时进行合并。它可以像你想要的那样复杂;但这是一个开始:
$("div").each(function (i) {
$(this).find("*").each(function () {
var that = this.previousSibling;
if (that && that.nodeType === Node.ELEMENT_NODE && that.tagName === this.tagName) {
var node = document.createElement(this.tagName);
while (that.firstChild) {
node.appendChild(that.firstChild);
}
while (this.firstChild) {
node.appendChild(this.firstChild);
}
this.parentNode.insertBefore(node, this.nextSibling);
that.parentNode.removeChild(that);
this.parentNode.removeChild(this);
}
});
});
关于javascript - 在 jQuery 中将直接 HTML 兄弟合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21760378/