最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to get event target without jQuery - Stack Overflow

matteradmin4PV0评论

I have been trying to get the target (<li> element) from the mouseenter event but so far no luck!

The code:

<ul id="ul">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>

<script>
    var ul = document.getElementById('ul');

    ul.onmouseenter = function(e) {
        console.log(e.target);
    };
</script>

Unfortunately the console keeps printing the <ul /> element. Any suggestions?

I have been trying to get the target (<li> element) from the mouseenter event but so far no luck!

The code:

<ul id="ul">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>

<script>
    var ul = document.getElementById('ul');

    ul.onmouseenter = function(e) {
        console.log(e.target);
    };
</script>

Unfortunately the console keeps printing the <ul /> element. Any suggestions?

Share Improve this question asked Oct 16, 2013 at 4:31 smailismaili 1,2359 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

It's because the onmouseenter event is not a "bubbling" event, so it only fires when you enter the UL element, not when you enter nested elements, like the LI elements.

Therefore the e.target and the this elements will both be the UL.

If you use onmouseover instead it'll bubble, so you'll get the LI as the e.target when entering the LI elements.

You can get the targeted li like:

function getEventTarget(e) {
    e = e || window.event;
    return e.target || e.srcElement; 
}

var ul = document.getElementById('ul');
ul.onclick= function(event) {
    var target = getEventTarget(event);
    console.log(target.innerHTML);
};
Post a comment

comment list (0)

  1. No comments so far