javascript - html 中的 Jquery <br> 在展开期间导致连续的文本节点

标签 javascript jquery html

考虑我的三部分代码

<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.
});

Example

关于javascript - html 中的 Jquery <br> 在展开期间导致连续的文本节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26270842/

相关文章:

Javascript/HTML - 用 onclick 重复一个函数

javascript - 复制 Pinterest Facebook 邀请功能

jquery构建http查询字符串

javascript - 在 window.onbeforeunload 事件中使用 window.event.keyCode 在 javascript 中捕获 f5 按键事件始终为 0 而不是 116

html - CSS 中的堆叠不透明度有多不透明?

javascript - 连接到数据库的复选框的子复选框

javascript - 使用 Javascript 在文本区域内写入

html - 如何在不重复选择器的情况下为具有不同祖先的后代编写 Sass?

html - 将 HTML 选项与父选择的右边缘对齐

javascript - Vue-auth 在 vuex 操作中访问 $auth