Identify word on Javascript onhover

寵の児 提交于 2019-12-23 03:00:28

问题


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

They has the code:

<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>

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)?

Thanks in advance!


回答1:


jsFiddle Demo

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

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

And then also do this lower for the hover. You will need to use find on the set for the nested spans.

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


来源:https://stackoverflow.com/questions/20805512/identify-word-on-javascript-onhover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!