插入跨度后合并文本节点 [英] Merging Text Nodes Together After Inserting Span

查看:102
本文介绍了插入跨度后合并文本节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展,用于存储/检索用户选择的DOM结构的一部分(总是选择屏幕上的文本)。在存储选择内容时,我将该部分放在SPAN标记中,并用黄色突出显示文本。这会导致所选文本周围的DOM结构分裂成各种文本节点。这对我造成了一个问题,因为当我尝试恢复此选择时(不刷新页面),它会在DOM结构被修改时导致问题。

I have an extension where I am storing/retrieving a section of the DOM structure (always a selection of text on the screen) the user has selected. When I am storing a selection, I enclose the section in a SPAN tag, and highlight the text in yellow. This causes the DOM structure around the selected text to split up into various text nodes. This causes a problem for me as when I try to restore this selection (without refreshing the page) it causes problems as the DOM structure has been modified.

我的问题是插入SPAN后,我是否防止DOM结构分裂?如果无法实现,那么在将SPAN标记移除到原始状态后,如何重新组合DOM结构?

My question is how do I prevent the DOM structure from splitting up after inserting the SPAN? If this cannot be achieved, how would I reassemble the DOM structure after removing the SPAN tag to its original state?

//Insert the span
var sel = restoreSelection(mootsOnPage[i].startXPath);
var range = sel.getRangeAt(0).cloneRange();
var newNode = document.createElement('span');
newNode.className = 'highlightYellow';
range.surroundContents(newNode); 


//Original DOM structure
<p>Hello there, how are you today</p>


//What the DOM looks like after insertion of SPAN
<p>
  "Hello there, "
  <span class="highlightYellow">how</span
  " are you today"
</p>


推荐答案

您可以使用它来展开您的内容。

You can use this to unwrap your content.

$(".highlightYellow").contents().unwrap(); 

演示: http://jsfiddle.net/R4hfa/

这篇关于插入跨度后合并文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆