使用Javascript获取单击单词的句子 [英] Use Javascript to get the Sentence of a Clicked Word
本文介绍了使用Javascript获取单击单词的句子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我遇到的一个问题,我不太清楚如何处理它。
This is a problem I'm running into and I'm not quite sure how to approach it.
说我有段落:
"This is a test paragraph. I love cats. Please apply here"
我希望用户能够单击句子中的任何一个单词,然后返回包含它的整个句子。
And I want a user to be able to click any one of the words in a sentence, and then return the entire sentence that contains it.
推荐答案
您首先必须将段落拆分为元素,因为您无法(轻松)检测没有元素的文本点击:
You first would have to split your paragraph into elements, as you can't (easily) detect clicks on text without elements :
$('p').each(function() {
$(this).html($(this).text().split(/([\.\?!])(?= )/).map(
function(v){return '<span class=sentence>'+v+'</span>'}
));
});
请注意,它会正确拆分这样的段落:
Note that it splits correctly paragraphs like this one :
<p>I love cats! Dogs are fine too... Here's a number : 3.4. Please apply here</p>
然后你会绑定点击:
$('.sentence').click(function(){
alert($(this).text());
});
我不知道英文是否:
是一个分隔符句子。如果是这样,它当然可以添加到正则表达式中。
I don't know if in English :
is a separator between sentences. If so, it can be added to the regex of course.
这篇关于使用Javascript获取单击单词的句子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文