使用getSelected()获取所选文本的跨度ID [英] Get span Id's of selected text using getSelected()

查看:98
本文介绍了使用getSelected()获取所选文本的跨度ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题。我不太清楚如何处理它。我们有一个应用程序,它会发出文本段落,每个单词都包含在带有ID的范围内。我被要求创建一个JavaScript来捕获用户突出显示的所有单词的ID。

I have a weird problem. I don’t quite know how to approach it. We have an application that spits out paragraphs of text with each and every word wrapped in a span with an ID. I am being asked to make a JavaScript to capture the ID's of all the words that a user highlights.

所以下面是一个简单的段落示例。

So a simple example of a paragraph is below.

<span id="p-58" class="softWord" onClick="setTranscriptPosition(-58);return false"> that </span>
<span id="p177" class="softWord" onClick="setTranscriptPosition(177);return false"> quake </span>
<span id="p857" class="softWord" onClick="setTranscriptPosition(857);return false"> briefly </span>
<span id="p1697" class="softWord" onClick="setTranscriptPosition(1697);return false"> triggering </span>
<span id="p2267" class="softWord" onClick="setTranscriptPosition(2267);return false"> another </span>
<span id="p2697" class="softWord" onClick="setTranscriptPosition(2697);return false"> tsunami </span>

我知道有一种方法可以使用以下内容捕获所选文本:(在网站上找到这个 http://motyar.blogspot.com /2010/02/get-user-selected-text-with-jquery-and.html

I know there is a way to capture the selected text using something like this:(found this at site http://motyar.blogspot.com/2010/02/get-user-selected-text-with-jquery-and.html)

function getSelected() {
    if(window.getSelection) { return window.getSelection(); }
        else if(document.getSelection) { return document.getSelection(); }
                    else {
                            var selection = document.selection && document.selection.createRange();
                            if(selection.text) { return selection.text; }
                return false;
            }
            return false;
        }

我如何获得这些跨度的ID?

How would i get the id's of those spans though?

推荐答案

好的,这将完全符合您的需要。这要归功于我朋友在我们共同完成的项目上所做的工作,所以归功于他:

Ok, this will do exactly what you need. It's thanks to my friend's work on a project we did together, so the credit belongs to him:

http://jsfiddle.net/KC48j/11/

只需选择一些文字并按下按钮即可。 EDIT :已更新为与IE合作。你可以自己搞乱逻辑(它如何处理单词之间的空格取决于你)。

Just select some text and hit the button. EDIT: updated to work with IE as well. You can mess around with the logic yourself (how it handles whitespace between words is up to you).

这篇关于使用getSelected()获取所选文本的跨度ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆