简体   繁体   中英

Getting ID of DOM Element using $(document).on & mouseenter/mouseleave

Good Morning,

I'm currently looking for a solution to get the DOM element id on two occasions.

  • Occasion one: When the mouse enters a div get the ID of the div its entered.
  • Occasion two: When the mouse leaves a div get the ID of the div it left.

It's dynamic content therefore I have the following base code:

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

    },
    mouseleave: function(e) {

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

However, I'm having problems getting the actual id of the element on the above two occasions.

Thanks for your help!

You can simply use this.id , assuming your .template-builder-template-stream-slot element actually has an ID when this code is fired. If it doesn't have an ID, the result will be blank.

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

If we move our cursor over both of these from top to bottom, we'll get the following result in our JavaScript console (note how the last element, which has no ID, returns no value (an empty string)):

控制台日志

You may use this or e.target.id . For more you may visit Getting the ID of the element that fired an event

Both this and e.target refer to the target element:

var id = e.target.id;
var id = this.id;

If this value is an empty String, the target element does not have an id attribute.

You could verify that this is the case by logging the target elements:

$(document).on({
    mouseenter: function(e) {
        console.log(this); // logs a DOM element
        console.log(this.id); // logs the id if present, or blank otherwise.
    }
}, '.template-builder-template-stream-slot');

您可以使用“ e.target.id”来访问mouseenter和mouseleave方法中的元素的id。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM