0

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

我的真实环境更复杂,但我已将其简化为基础,以缩小解决方案的范围。非常感谢任何帮助/建议。

4

2 回答 2

2

使用该.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
于 2013-05-24T00:29:10.367 回答
2

这是一个将考虑spans 开始和结束位置的函数。使用纯 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]]
    
于 2013-05-24T02:16:44.780 回答