考虑我的三部分代码
<div>
Lorem Ispum dolor sit <span class='highlightYellow'>Amet </span>
<br />Lorem Ispum <span class='highlightYellow'>dolor</span> sit Amet
</div>
<div>
Lorem Ispum dolor sit <span class='highlightYellow'>Amet </span>
Lorem Ispum <span class='highlightYellow'>dolor</span> sit Amet
<br />
</div>
<div>
Lorem Ispum dolor sit <span class='highlightYellow'>Amet </span>
Lorem Ispum <span class='highlightYellow'>dolor</span> sit Amet
</div>
和一个按钮
<button>Unwrap text from .hightlightYellow elements</button>
我正在使用这种方法来解包
$(".highlightYellow").contents().unwrap();
当看到<div>
的子节点时, 类似 $('div')[i].childNodes
由于 <br/>
标签,div内的内容变成多个连续的文本节点。两个texnode怎么一个接一个来?这真的不可能。但它来了。
在第三个<div>
, 没有 <br/>
标签。所以它工作正常。我猜到了 <br/>
标记只会导致此问题。或者有没有其他方法可以克服这个问题?
这是 Fiddle ,您可以通过检查元素来查看问题
最佳答案
http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-1312295772
When a document is first made available via the DOM, there is only one Text node for each block of text. Users may create adjacent Text nodes that represent the contents of a given element without any intervening markup, but should be aware that there is no way to represent the separations between these nodes in XML or HTML, so they will not (in general) persist between DOM editing sessions. The normalize() method on Element merges any such adjacent Text objects into a single node for each block of text; this is recommended before employing operations that depend on a particular document structure, such as navigation with XPointers.
$('div').each(function(i, element) {
element.normalize();
//The normalize() method removes empty Text nodes, and joins adjacent Text nodes.
});
关于javascript - html 中的 Jquery <br> 在展开期间导致连续的文本节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26270842/