Use Javascript to get the Sentence of a Clicked Word

后端 未结 5 2075
甜味超标
甜味超标 2021-02-05 21:37

This is a problem I\'m running into and I\'m not quite sure how to approach it.

Say I have a paragraph:

\"This is a test paragraph. I love cats. Please a         


        
5条回答
  •  伪装坚强ぢ
    2021-02-05 22:16

    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 ''+v+''}
       ));
    });
    

    Note that it splits correctly paragraphs like this one :

    I love cats! Dogs are fine too... Here's a number : 3.4. Please apply here

    Then you would bind the click :

    $('.sentence').click(function(){
        alert($(this).text());
    });
    

    Demonstration

    I don't know if in English : is a separator between sentences. If so, it can be added to the regex of course.

提交回复
热议问题