标识Javascript onhover上的单词 [英] Identify word on Javascript onhover

查看:146
本文介绍了标识Javascript onhover上的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过stackoverflow查看此链接(如何使用JavaScript在光标下使用字词

I was looking through stackoverflow and came across this link(how to get a word under cursor using JavaScript)

他们有代码:

<p>Each word will be wrapped in a span.</p>
<p>A second paragraph here.</p>
Word: <span id="word"></span>

<script type="text/javascript">
    $(function() {
        // wrap words in spans
        $('p').each(function() {
            var $this = $(this);
            $this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
        });

        // bind to each span
        $('p span').hover(
            function() { $('#word').text($(this).css('background-color','#ffff66').text()); },
            function() { $('#word').text(''); $(this).css('background-color',''); }
        );
    });
</script>

当我尝试这个时,我意识到这个代码将只适用于段落标签。我应该如何编辑这个代码的Javascript /正则表达式,使其工作将所有的标签(h1,h2,h3)?

When I tried this out, I realized this code will only work with paragraph tags. How should I edit the Javascript/Regex of this code to make it work will all tags(h1,h2,h3)?

提前感谢!

推荐答案

jsFiddle Demo

jsFiddle Demo

进行一些调整。将选择器更改为包含 h1,h2,h3

Make a few adjustments. Change the selector to include h1,h2,h3

$('p,h1,h2,h3').each(function() {

$('p,h1,h2,h3').find("span").hover(

这篇关于标识Javascript onhover上的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆