使用Javascript的所选单词的索引

如何使用Javascript在HTML中获取所选文本的索引?
例如,在HTML文件中,有如下段落:

I am living in India. India is the very beautiful country.

现在,如果用户在第一句中选择印度,则应该有警报5,如果用户选择第二行的印度,则存在警报6.

如何获取用户选择的单词的索引?

解决方法:

您可以使用我的Rangy library的新TextRange module执行此操作.Rangy的Range对象具有moveStart()和moveEnd()方法,允许您在任一方向上一次扩展一个单词的范围.

这是一个演示:http://jsfiddle.net/timdown/ArMHy/

码:

var sel = rangy.getSelection();
if (sel.rangeCount > 0) {
    var range = sel.getRangeAt(0);

    // Expand the range to contain the whole word
    range.expand("word");

    // Count all the preceding words in the document
    var precedingWordCount = 0;
    while (range.moveStart("word", -1)) {
        precedingWordCount++;
    }

    // Display results
    alert("Selection starts in word number " + (precedingWordCount + 1));        
}
上一篇:android-我的微调器未调用OnItemSelectedListener()


下一篇:table选中某条数据删除功能