JQuery assign events to buttons

前端 未结 8 818
小蘑菇
小蘑菇 2020-12-11 23:43

I have 50 dynamically generated HTML buttons as follows:




        
相关标签:
8条回答
  • 2020-12-12 00:06

    Try

    $(".btn").click(function() {
        // Do something
    });
    
    0 讨论(0)
  • 2020-12-12 00:14

    Event listeners cost memory. You have to think carefully about how you should implement the listeners.

    1. The straightforward way:

    Do not use this

    If the behaviour for each button is the same, use a class:

    $(".btn").click(function() {
        // Do something
    });
    

    If behaviour for each button is different, assign events to different #IDs

    $("#btn1").click(function {
        // Do something
    });
    

    2. Use .on():

    jQuery 1.7 introduced .on() method that wraps all listeners to 1 method.

    $("button").on("click", function() {
        // Do something
    });
    

    However, we are still binding many listeners on the page.

    3. Use a wrapper (use this!):

    Wrap your buttons with a div and create one listener for it.

    $("#wrapper").on("click", "button", function() {
        // Do something
    });
    

    Useful resources:

    • Performance comparison
    • .on()
    0 讨论(0)
提交回复
热议问题