javascript - 使用 $(document).on & mouseenter/mouseleave 获取 DOM 元素的 ID

标签 javascript jquery asp.net dom

早上好,

我目前正在寻找一种解决方案来两次获取 DOM 元素 id。

  • 场景一:当鼠标进入一个div时,获取该div的ID 进入。
  • 情况二:当鼠标离开div时获取该div的ID div 向左移动。

它是动态内容,因此我有以下基本代码:

$(document).on({
    mouseenter: function(e) {

    },
    mouseleave: function(e) {

    }
}, '.template-builder-template-stream-slot');

但是,我在上述两种情况下获取元素的实际 id 时遇到问题。

感谢您的帮助!

最佳答案

您可以简单地使用 this.id,假设您的 .template-builder-template-stream-slot 元素在触发此代码时实际上有一个 ID。如果没有 ID,结果将为空。

$(document).on({
    mouseenter: function(e) {
      console.log("mouseenter on #" + this.id);
    },
    mouseleave: function(e) {
      console.log("mouseleave on #" + this.id);
    }
}, '.example');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<figure class="example" id="one">This has an ID of "one".</figure>
<figure class="example" id="two">This has an ID of "two".</figure>
<figure class="example">This has no ID at all.</figure>

如果我们将光标从上到下移动到这两个元素上,我们将在 JavaScript 控制台中得到以下结果(请注意最后一个没有 ID 的元素如何返回任何值(空字符串)):

Console Log

关于javascript - 使用 $(document).on & mouseenter/mouseleave 获取 DOM 元素的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27796965/

相关文章:

asp.net - 使用 web 部署参数时使用 web.config 中的默认值

javascript - 从串联函数谷歌脚本中删除不需要的分隔符

javascript - 尽管端口转发正常,但应用程序无法向本地主机发出请求

php - 如何将 SELECT ALL 值或 SELECTED 复选框值插入到 mysql 中的不同列中?

javascript - jQuery - 在函数中使用计算+变量来改变css

javascript - 填写输入字段时,标签仍然下降

javascript - Gulp browser-sync 不监控和注入(inject)文件

javascript - Polymer 2 条件属性

c# - Global 和 IProcessHostPreloadClient 中的 Application_Start

c# - 如何在 ASP.net razor 网页中使用 "Using"语句?