JavaScript:需要查找给定字符串中多个子字符串中的哪一个已被选择(突出显示)

发布于 2025-01-06 10:23:07 字数 573 浏览 1 评论 0原文

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

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)索引)。

非常感谢任何帮助。

Given any block of text, using the following as an example:

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

I need to determine, using JavaScript (use of jQuery is fine), which of the three instances of "baseball" as been selected by the user. I have code in place that will wrap the selected text in a span, which may help in figuring this problem out.

Assuming that the user selects the second occurrence of baseball, the HTML will look similar to this:

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

Essentially I'm looking for a solution on how to determine that the selected 'baseball' is occurrence #2 (or 1 in the case of zero-indexing).

Any help is greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

耀眼的星火 2025-01-13 10:23:07

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 + "'");
}

Live demo: http://jsfiddle.net/kGE7e/

The Selection object will tell you exactly what is selected:

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);
}

For your example, assuming you have a single text node containing all your text, you could do something like:

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 + "'");
}

Live demo: http://jsfiddle.net/kGE7e/

柒夜笙歌凉 2025-01-13 10:23:07

用 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>

After wrapping the words with span you can do it this way, using 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>
呢古 2025-01-13 10:23:07

由于我使用正则表达式来解析 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');

I'll probably get downvoted for this since I am using regexes to parse html, but I think it does what you want

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');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文