JavaScript:需要查找给定字符串中多个子字符串中的哪一个已被选择(突出显示)
给定任何文本块,使用以下示例:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Selection
对象将准确告诉您选择的内容:您的示例,假设您有一个包含所有文本的文本节点,您可以执行以下操作:
Live demo: http://jsfiddle.net/kGE7e/
The
Selection
object will tell you exactly what is selected:For your example, assuming you have a single text node containing all your text, you could do something like:
Live demo: http://jsfiddle.net/kGE7e/
用 span 包裹单词后,您可以使用 JQuery 这样做
After wrapping the words with span you can do it this way, using JQuery
由于我使用正则表达式来解析 html,因此我可能会对此投反对票,但我认为它可以满足您的要求
I'll probably get downvoted for this since I am using regexes to parse html, but I think it does what you want