获取有关jquery中单击事件的段落中的当前单词

Pat*_*ery 5 jquery cpu-word

我正在尝试构建一个工具,允许人们获取单词或短语(在选择上),选择部分已完成,但不是单词部分.

当有人点击一个单词时,我需要能够得到当前的单词,我找到了这个解决方案

得到单词点击段落

不幸的是,这段代码更改了所有单词并<span>为每个单词添加了一个,这导致了我身边的问题,因为我无法在文本中添加html标签(css文件可以导入或动态添加)

如果可能的话,是否有更好的方法来实现这一目标?

EX:

Lorem ipsum dolor坐下来,精致的adipistur elit.Donec auctor ante坐在amet nisl consequat volutpat.

如果我点击"坐",那么我会提醒'坐'

Osc*_*car 15

那么,对于您的解决方案,您将需要使用selectionsdoubleclick事件作为一个棘手的事情,并通过doubleclick事件获取生成范围内的选定单词.

如果您不想引入新标签,则没有其他办法.


试试这个:

现场演示: http ://jsfiddle.net/oscarj24/5D4d3/

$(document).ready(function() {

    /* set hand cursor to let know the user that this area is clickable */
    var p = $('p');
    p.css({ cursor: 'pointer' });

    /* doubleclick event working with ranges */
    p.dblclick(function(e) {
        var selection = window.getSelection() || document.getSelection() || document.selection.createRange();
        var word = $.trim(selection.toString());
        if(word != '') {
            alert(word);
        }
        /* use this if firefox: selection.collapse(selection.anchorNode, selection.anchorOffset); */
        selection.collapse();
        e.stopPropagation();
    });

});?
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 :-)