早上好,
我目前正在寻找一种解决方案来两次获取 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 的元素如何返回任何值(空字符串)):
关于javascript - 使用 $(document).on & mouseenter/mouseleave 获取 DOM 元素的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27796965/