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
1.1k views
in Technique[技术] by (71.8m points)

javascript - How to detect a click on a list element?

I have this html code:

<div id="wordListDiv">
    <ul>
        <li id="word_0">bateau</li>
        <li id="word_1">braguette</li>
        <li id="word_2">bateau</li>
    </ul>
</div>

Then I have a javascript file:

document.addEventListener( 'click', mouseEventsListener);

function mouseEventsListener ( event ) {

    switch( event.target ) {

        case ***HOW_TO_DETECT_CLICK_ON_THE_LI_ELEMENTS***:

            myFunction( parameter );

        break;

    default:
        
        break;

    }

}

How can I execute myFunction from within the switch/case statement when the user clicks on a "li" element?


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

1 Answer

0 votes
by (71.8m points)

Check this code and as mention in above comment you can add more check as per your need

document.addEventListener( 'click', mouseEventsListener);

function mouseEventsListener ( event ) {

    
    switch( event.target.tagName ) {

        case 'LI':
            alert('Clicked LI')
            //myFunction( parameter );

        break;

    default:
        
        break;

    }

}
<div id="wordListDiv">
    <ul>
        <li id="word_0">bateau</li>
        <li id="word_1">braguette</li>
        <li id="word_2">bateau</li>
    </ul>
</div>

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

...