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 タグを元の場所に戻すことを検討する必要があるソリューションが必要なため、上記の関数には 3 つの可能な出力があります。

  • 要素の配列:

    ["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 に答える