激活某个单词的悬停操作

时间:2015-09-25 16:22:49

标签: javascript jquery html hover

好的,所以这已经完成了,所以我知道这是可能的。我想要的是,当用户将鼠标悬停在wordHoverAssign()函数定义的某个单词上时,会激活某些内容。

因此,以更简洁的方式:当页面加载时,文本我爱土豆!显示在屏幕上,用HTML创建。然后执行函数wordHoverAssign("potatoes")。当我将鼠标悬停在 potato 这个词时,会发生什么情况,会弹出一条警告消息,例如,此消息你徘徊了这个词!

这可能吗?我该怎么做呢?如果我不必再使用任何框架/插件,我真的很喜欢它。我顺便使用jQuery。

谢谢。

到目前为止我的代码(如果您不想设置它):



wordHoverAssign("potatoes");

function wordHoverAssign(theWord) {
  //code here
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>I love potatoes!</p>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

根据您的需要:contains('text')更适合您。见例子:

wordHoverAssign("potatoes");

function wordHoverAssign(theWord) {
  $( ":contains("+theWord+")" ).hover(function(){
      alert("Hover happend");
  })
}

这是Updated DEMO

但是上面的代码会因为悬停事件也会与body绑定两次提醒,所以我的建议是使用特殊标记。请参阅以下代码段:

wordHoverAssign("potatoes");

function wordHoverAssign(theWord) {
  $( "p:contains("+theWord+")" ).hover(function(){
      alert("Hover happend");
  })
}

另一个DEMO用于悬停在p代码中。它不会对身体悬停起作用。

答案 1 :(得分:1)

以下内容允许您为#content div中的任何单词指定不同的功能。只有在特定单词悬停时才会调用相关函数。

<div id="content">
    I love potatoes!<br/>
    She loves something else<br/>
    The potatoes coming again.
</div>

<script>
    window.wordsAssigned = {};
    function wordHoverAssign(word,func){
        wordsAssigned[word] = func;
    }

    wordHoverAssign('potatoes',function(){
        alert('Patatoes hovered!');
    });
    wordHoverAssign('something else',function(){
        alert('something else!');
    });

    $(function(){
        var content = $('#content');
        var html = content.html();
        for(var word in wordsAssigned){
            html = html.replace(new RegExp(word,"gm"),'<span onmouseover="wordsAssigned[\''+word+'\']()">'+word+'</span>');
        }
        content.html(html);
    })
</script>