jQuery - 当我的鼠标悬停在任何单词上时,如何获取任何单词的值

jQuery - How can I get the value of any word when my mouse is hovering over it

本文关键字:任何单 何获取 获取 我的 鼠标 悬停 jQuery      更新时间:2023-09-26

在jQuery中,当我的鼠标悬停在元素内的单词上时,我想获取它的值。

例如,如果我有一个包含此文本的段落

<p>This is a paragraph</p>

当我将鼠标悬停在某个特定单词上时,例如 this ,我想获取其文本。

对于每个div,我们搜索每个单词并将其包装在span标签中。

我们将收听mouseover事件并添加一个突出显示类,以突出显示我们定位的单词。然后我们可以得到那个跨度的html。我们删除mouseout事件的类。

$('div').each(function() {
    $(this).html($(this).text().replace(/'b('w+)'b/g, "<span>$1</span>"));
});
$('div span').on("mouseover", function() {
    $(this).addClass('highlight'); 
        $("#result").html(getWord($(this).html()));
    }).on("mouseout", function() {
        $(this).removeClass('highlight'); 
    });
function getWord(word){
    return word;
}
span {
  font-size: 15pt;
}
.highlight {
  background: #ffff66;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>This text is a  test text</span>
</div>
<p id="result"></p>

$(document).ready(function(e) {
  $("*").not("body").mouseover(function() {
    alert($(this).text());
  }); 
});

这段代码适用于除正文标签以外的所有标签。

//everything on the page, avoiding the body, who has the entiry text of the page
$(document).on('mouseenter',':not(body)',function(){
//1 - get the text 
    var text = $(this).text();
    //2 - verify if text is not empty
    if(text != ''){
        //3 - break the text by lines, you choose
           text = text.split(''n');
        //4- get only the first line, you choose
           text = text[0];
        //5 verify again if is not empty
           if(text != ''){
               //write on console
               console.log(text);
            }
     }
});