在jquery中的click事件中获取段落中的当前单词 [英] Get the current word in paragraph on click event in jquery
问题描述
我正在尝试构建一个工具,使人们能够(选择时)获得单词或短语,选择部分已完成,但单词部分却未完成.
I am trying to build a tool that allow people to get word or a phrase (on select), the select part is done but not the word part.
当有人点击某个单词时,我需要能够获得当前单词,而我找到了这种解决方案
I need to be able to get the current word when someone click on a word, and i found this solution
不幸的是,此代码更改了所有单词,并为每个单词添加了<span>
,这在我这一边引起了问题,因为我无法在文本中添加html标签(css文件可以动态导入或添加)
unfortunately, this code change all the words and add a <span>
for every words, which causes an issue on my side since i cannot add html tags in the text (css file can be imported or added dynamically)
如果可能的话,还有更好的方法吗?
is there's a better way to accomplish this, if possible?
EX:
Lorem ipsum dolor坐着,安全奉献精英.多内克·奥克托 事前请准时结束.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec auctor ante sit amet nisl consequat volutpat.
如果我单击坐下",那么我将提醒坐下"
if i click on "sit", then i will alert 'sit'
推荐答案
好,对于您的解决方案,您将需要处理selections
和doubleclick
事件,这很棘手,并通过doubleclick事件.
Well, for your solution you will need to work with selections
and doubleclick
event as a tricky thing and get the selected word in the generated range by the doubleclick event.
如果您不想引入新标签,则没有其他方法.
尝试一下:
实时演示: 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();
});
});
希望这会有所帮助:-)
Hope this helps :-)
这篇关于在jquery中的click事件中获取段落中的当前单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!