1

次の例を使用して、任意のテキスト ブロックを指定します。

Baseball is a sport. 
A pitcher throws the baseball and the batter hits the baseball.

JavaScript を使用して (jQuery の使用は問題ありません)、「baseball」の 3 つのインスタンスのどれがユーザーによって選択されたかを判断する必要があります。選択したテキストをスパンでラップするコードが用意されているため、この問題を解決するのに役立ちます。

ユーザーが野球の 2 番目のオカレンスを選択すると仮定すると、HTML は次のようになります。

Baseball is a sport. 
A pitcher throws the <span class="selection">baseball</span> and the batter hits the baseball.

基本的に、選択された「野球」が出現#2(またはゼロインデックスの場合は1)であることを判断する方法に関する解決策を探しています。

どんな助けでも大歓迎です。

4

3 に答える 3

2

オブジェクトは、Selection何が選択されているかを正確に教えてくれます:

var sel = window.getSelection();
if (sel.rangeCount) {
    var range = sel.getRangeAt(0);
    alert("Selection goes from offset " + range.startOffset + " in "
        + range.startContainer.nodeValue + " to offset " + range.endOffset
        + " in " + range.endContainer.nodeValue);
}

あなたの例では、すべてのテキストを含む単一のテキスト ノードがあると仮定すると、次のようなことができます。

if (range.startContainer.nodeType == 3) {
    var textPriorToSelection = range.startContainer.data.slice(0, range.startOffset);
    var priorOccurrences = textPriorToSelection.split(sel.toString()).length - 1;
    alert("Occurrence " + (priorOccurrences + 1) + " of text '" + sel + "'");
}

ライブデモ: http://jsfiddle.net/kGE7e/

于 2012-02-16T15:48:10.383 に答える
0

正規表現を使用してhtmlを解析しているので、おそらくこれに反対票を投じるでしょうが、それはあなたが望むことをするのだと思います

var matches = "Baseball is a sport. A pitcher throws the <span class='selection'>baseball</span> and the batter hits the baseball.".match(/<span.*?>baseball<\/span>|baseball/gi);
for(i=0;i<matches.length;i++)
    if(matches[i].indexOf('selection')!=-1)
        console.log(i+'th index of baseball is selected');
于 2012-02-16T16:14:29.383 に答える
0

単語をスパンでラップした後、JQueryを使用してこのようにすることができます

<div id="parent">
<span>Baseball</span> is a sport. 
A pitcher throws the <span>baseball</span> and the batter hits the <span>baseball</span>.
</div>
<script>
     $("#parent span").click(function() {
        var index = $("#parent span").index(this);
        alert(index);
        //add class?
        $(this).addClass("selection");
    });
</script>
于 2012-02-16T15:56:05.163 に答える