当鼠标悬停在文本中的单词上时显示警报

display alert when mouse hovers over word in text

本文关键字:显示 单词 悬停 鼠标 文本      更新时间:2023-09-26

我已经为此挣扎了几天。我需要有人引导我朝着正确的方向前进。我一直在网上搜索。我不确定我是否采取了正确的做法。我需要的是,每当一个人悬停在某个特定的关键词上时,它都应该显示一个警告框。在这个例子中,单词是else。当我运行代码时,它不会给出任何错误,当鼠标悬停在单词上时也不会显示任何内容。

function on_func2()
{
    var searchString = 'else';
    var elements = document.getElementById('paragraph2');
    for (var i = 0; i < elements.length; i++)
    {
        if (elements[i].innerHTML.indexOf(searchString) !== -1) 
        {
            alert('Match');
            break;
        }
    }
}

我会这样做:它将遍历并找到所有的else单词,并将它们封装在一个绑定了监听器的跨度中:

<p id="hello">What else would you say?</p>

-

​var hello = document.getElementById('hello');
var str = hello.innerHTML;
str = str.replace(​​​ /'b(else)'b/g, '<span onmouseover="func1()">$1</span>' );​​​​​​​​​​​​​​​​​​​
hello.innerHTML = str;
function func1() {
  alert('there');
}

看看小提琴。

使用jQuery刻字插件

<p class="word_split">if you were not there, else I would not have won.<p>

$(".word_split").lettering('words');
$('.word_split').mouseover(function(event) {
    var word=event.target.innerHTML;
    if (word == "else")
       alert("Yep");
});

这里有一个演示:jsFiddle