1

给定任何文本块,使用以下示例:

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

我需要使用 JavaScript(可以使用 jQuery)来确定用户选择了三个“棒球”实例中的哪一个。我有代码可以将选定的文本包装在一个跨度中,这可能有助于解决这个问题。

假设用户选择了第二次出现的棒球,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

用 span 包装单词后,你可以这样做,使用 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 回答
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 回答