获取文本块中的元素索引
Get elements index with in text block
是否可以在文本块中获得标签位置?例如,我有一个巨大的p标签,里面有一堆文本。用户将有一个工具,它将动态地插入一堆span标签到p标签。在某一点上,用户将完成,我想保存他们所做的。由于限制,我无法保存p标签的整个内容,而是必须获得每个单独的span。
起始文本
<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);
});
});
我的实际环境更复杂,但我已将其简化为基本内容以缩小解决方案的范围。非常感谢任何帮助/建议。
使用.contents
方法获取段落的所有子节点,包括文本节点。现在你可以很容易地遍历它们:
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
这里有一个函数,它将考虑到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
查看此处的示例演示。
由于您需要的解决方案需要考虑将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]]
相关文章:
- 如何索引jquery中的每个元素
- JavaScript DOM:在容器中查找元素索引
- 通过javascript中的元素索引访问eventListener中的元素
- 将页面元素索引到 JSON 对象?或者jQuery选择器它每次
- jQuery将相同的类添加到两个不同容器中的同一元素索引中
- 获取小元素索引直到数组长度
- jQuery获取元素索引,尽管包装器/父元素
- 更改数组中某些元素(索引)的顺序
- 访问具有公共类名的元素数组中的元素索引
- 访问循环的内部的ES6数组元素索引
- 列表类元素(索引).渐变(某些速度)不起作用
- javascript中的表单元素索引,用于jquery.change函数
- 获取文本块中的元素索引
- 用主干JS .get模型事件连接元素索引
- 从81个元素索引的数组中获取行和列值
- 如何使用javascript获得元素索引
- 使用类和子类获取元素索引
- Mootools从父元素获取子元素索引
- 如何在Javascript中获得一组固定元素的元素索引
- 使用jQuery更改列表元素索引