Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

javascript - addEventListener only to the direct children

I'm trying to add an event on all the children of ul. (In this case li elements)

The problem is that it adds an event to its children as well (a elements).

let myElements = document.querySelectorAll('ul > li');

for (let i = 0; i < myElements.length; i ++ ) {
    myElements[i].addEventListener('mouseover', () => {
        console.log('Event !!!')

    });

}
li {
        background: rgb(226, 226, 226);
        border: 1px solid #000000;
        padding: 20px;
        margin: 20px;
    }

    a {
        background: rgb(255, 222, 219);
        border: 1px solid rgb(211, 65, 65);
        padding: 20px;
        margin: 20px;
        display: block;
    }
<ul>
    <li>
        <a href="#">1</a>
        <a href="#">2</a>

    </li>
    <li>
        <a href="#">3</a>
        <a href="#">4</a>
    </li>
    <li>
        <a href="#">5</a>
        <a href="#">6</a>
    </li>
</ul>
question from:https://stackoverflow.com/questions/65920842/addeventlistener-only-to-the-direct-children

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The solution is to use mouseenter instead of mouseover.

mouseenter only triggers when the mouse enters the element on which it is set.

mouseover triggers when the mouse enters the element or any of its children.

https://thisthat.dev/mouseenter-vs-mouseover/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...