Welcome to OGeek Q&A 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...