是否可以在文本块中获取标记位置。例如,我有一个巨大的p标签,其中有一堆文本。用户将拥有一个工具,可以将一堆span标签动态插入到p标签中。有一次,用户将完成,我想保存他们已经完成的工作。由于限制,我无法保存p标签的全部内容,而是必须获得每个单独的跨度。
初始文字
<p>Sam wanted a dog.
"If you're a good boy," said his father.
"When you can take care of it yourself" said his mother.
Sam cleaned up his room. He ate carrots and broccoli. He stopped making monster noises
at night to scare Molly, his older sister. He hung up his cap after baseball practice.
</p>
用户互动后
<p>Sam wanted a dog.
"If you're <span>a good boy,"</span> said his father.
"When you can take care of it yourself" said his mother.
Sam cleaned up his <span>room. He ate</span> carrots and broccoli. He stopped making monster noises
at night to scare Molly, his older sister. He hung up his cap after baseball practice.
</p>
我想我正在寻找的是跨度开始的范围以及结束的位置。到目前为止,我所能做的只是循环浏览内容,但我仍然坚持找到从那里去的地方。我需要保存的原因是因为用户希望以他们离开的方式返回其内容。因此,解决方案需要考虑将span标记放回原处。
我将如何开始的样本JS
$("p").each(function (index) {
$(this).find("span").each(function () {
console.log(this);
});
});
我的真实环境更复杂,但我已将其简化为基础知识,以缩小解决方案范围。非常感谢任何帮助/建议。
答案 0 :(得分:2)
使用.contents
method获取段落的所有子节点,包括文本节点。现在您可以轻松地遍历它们:
var ranges = [],
i = 0;
$("thatp").contents().each(function() {
var $this = $(this);
if (this.nodeType == 1 && $this.is("span"))
ranges.push([i, i+=$this.text().length]);
else
i+=$this.text().length;
});
// result:
> ranges
[[31,43],[141,153]] // at least in my console test, you might have different whitespaces
答案 1 :(得分:2)
这是一个考虑span
开始和结束位置的函数。使用纯JavaScript。
function getSpanRanges(myP) {
var start = -1, result = [], parts = [], partsTypes = [];
for (var i = 0; i < myP.childNodes.length; i++) {
parts[i] = myP.childNodes[i].outerHTML || myP.childNodes[i].nodeValue;
partsTypes[i] = myP.childNodes[i].nodeName;
if ("SPAN" == myP.childNodes[i].nodeName) { result.push([start + 1, start + parts[i].length]); }
start += parts[i].length;
}
return result;
}
使用示例:
var myP = document.getElementsByTagName("p")[0];
var spanRanges = getSpanRanges(myP); // this is the ranges array
<强> See EXAMPLE DEMO here 强>
由于您需要一个需要考虑将span标记放回去的解决方案,因此上述函数有三种可能的输出:
元素数组:
["Sam wanted a dog. \"If you're ", "<span>a good boy,\"</span>", " said his father. \"When you can take care of it yourself\" said his mother. Sam cleaned up his ", "<span>room. He ate</span>", " carrots and broccoli. He stopped making monster n…ster. He hung up his cap after baseball practice."]
他们的类型数组:
["#text", "SPAN", "#text", "SPAN", "#text"]
一个数组及其范围(起点,终点):
[[29, 53], [148, 172]]