给定任何文本块,使用以下示例:
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)的解决方案。
非常感谢任何帮助。
答案 0 :(得分: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 + "'");
}
答案 1 :(得分: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>
答案 2 :(得分: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');