【问题标题】:Get Element and ID, if any on mouseover with jQuery [duplicate]使用 jQuery 在鼠标悬停时获取元素和 ID(如果有)[重复]
【发布时间】:2017-03-30 04:12:19
【问题描述】:

我正在尝试为我的管理员提供他们悬停在其上的元素的 鼠标悬停,以便他们知道要编辑的内容(如果有的话)。这是我的代码:

$(document).tooltip();
$(document).on('mouseover','*',function(){
  $(this).attr('title',$(this).prop('id'));
  console.log($(this));
}).on('mouseout',function(){
  $(this).attr('title','');
});

这对于带有 id 的元素非常有用。我需要得到的是 html 元素和 mouseover 上的 id(如果有)的组合。

【问题讨论】:

  • 你说的“combo html element”是什么意思
  • 不清楚。在鼠标悬停时,您正在设置元素的标题。但是没有id的时候应该怎么办呢?
  • 我想要得到的是元素(body、div、span 等),它会很有帮助,但没有必要在元素上有一个 id
  • 我认为您想获取元素类型名称。如果是这样,那么您可以使用 $(this).prop('nodeName') 之类的代码

标签: jquery html


【解决方案1】:

如果我理解正确,当您将鼠标悬停在一个元素上时,您需要元素的 id 以及元素类型(标签名称)。如果是这种情况,那么您可以使用以下内容:

 $(document).on('mouseover','*',function(){
      var id = this.id;
      var elementType = $(this).prop('nodeName'); // will give you element tag name
      // do something with id and elementType
    }).on('mouseout',function(){
      $(this).attr('title','');
    });

【讨论】:

  • 感谢你们,我现在知道实际上还有其他帖子提出了同样的问题。我应该删除我的帖子吗?
  • @phpmydev 你不需要删除帖子。如果您接受重复的问题,您的问题可以作为寻找相同答案的其他人的路标。
【解决方案2】:

您应该能够使用 this.id 而不是 $(this)... 来缩短该代码 还要检查您的控制台并从那里选择您需要的 w/e,然后使用 || 运算符来选择最适合您的控制台。

$(document).on('mouseover','*',function(){
  $(this).attr('title',(this.id || some_other_things || yet_another_one));
  console.log($(this));
  console.log(this);
}).on('mouseout',function(){
  $(this).attr('title','');
});

【讨论】:

    【解决方案3】:

    如果未定义id,则获取dom元素的tagName属性。

    $(this).attr('title', this.id || this.tagName);
    

    【讨论】:

      猜你喜欢
      • 2013-06-04
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      相关资源
      最近更新 更多