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

jquery - How to add click event by class name?

I have a example html menu:

<div class="mmenu">
    <ul>
        <li>
            <div  class="menu_button" id="m1" >A</div>
        </li>
        <li>
            <div  class="menu_button" id="m2" >B</div>
        </li>
        <li>
            <div  class="menu_button" id="m3" >C</div>
    </ul>
</div>

Can I add click event for each element of menu by class name ?

 $('.menu_button').click(function() {
     if ( id == "m1" ) ....
 })
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Optimize your code by not using live() as we cannot stop propagation of live() events

Use on() (jQuery 1.7+) or delegate() (below 1.7)

Most efficient solution for your scenario in this case would be:

//  $('.mmenu').on("click", ".menu_button", function() {   // jQuery 1.7 & up
    $('.mmenu').delegate(".menu_button", "click", function() {
        var id = $(this).attr('id') // or this.id
        if ( id == "m1" ) {
            // ..code
        }
    });

In this way, you have only one click event bound to the main div $('.mmenu'), which will also work if you add elements (new li with divs) in the future


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

...