【问题标题】:Get ID of the element I hover over with jQuery?获取我用 jQuery 悬停的元素的 ID?
【发布时间】:2017-11-20 14:13:50
【问题描述】:

我有一堆看起来像这样的元素:

<span class='tags' id='html'>html</span>
<span class='tags' id='php'>php</span>
<span class='tags' id='sql'>sql</span>

如何获得我悬停在上面的 id 的名称,这样我就可以输出类似“你正在悬停在 html 标签上”的内容。 (我想做的不是那么随意,但我确实需要获取用户悬停在上面的标签的名称才能做到这一点。)

【问题讨论】:

    标签: jquery


    【解决方案1】:

    mouseover 应该可以解决问题。

    $('.tags').mouseover(function() {
       alert(this.id);
    });
    

    请注意,如果您还想知道鼠标何时离开,可以使用hover

    【讨论】:

    • 显示一个空的警告框。 =/.
    • 糟糕,我有两个名为“tags”的类意外;我制作了一个用于列表和一个用于格式化标签。呵呵。谢谢!
    【解决方案2】:
    $('.tags').hover(
      function() { console.log( 'hovering on' , $(this).attr('id') ); },
      function() {}
    );
    

    第二个空函数用于鼠标移出,您可能还想对该事件执行一些操作。

    【讨论】:

      【解决方案3】:

      这些解决方案仍然为我返回了一个空警报。对我来说,当我处理传递给悬停函数的事件对象时,以下工作:

      $(".input-box").hover(function(eventObj) { 
          alert(eventObj.target.id);  
      });
      

      Source of this solution

      【讨论】:

        【解决方案4】:

        Use this one:- 
        
            <!DOCTYPE html>
            <html>
            <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
            <script>
            $(document).ready(function(){
                $("p").hover(function(){
                
                    //if get onhover id
                    alert("NOW GET ON HOVER ID NAME:--"+" "+this.id);
                    
                    //if get onhover class
                    alert("NOW GET ON HOVER CLASS NAME:--"+" "+$(this).attr('class'));
                    
                    
                });
            });
            </script>
            </head>
            <body>
        
            <p class="getclass" id="get_class_id" >Hover the mouse</p>
        
            </body>
            </html>

        【讨论】:

          猜你喜欢
          • 2021-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-09
          • 2012-10-03
          • 2017-03-30
          • 2012-04-20
          • 1970-01-01
          相关资源
          最近更新 更多