获取文本块中的元素索引

Get elements index with in text block

本文关键字:元素 索引 取文本 获取      更新时间:2023-09-26

是否可以在文本块中获得标签位置?例如,我有一个巨大的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]]