JQuery assign events to buttons

2020-02-07 03:53发布

I have 50 dynamically generated HTML buttons as follows:

<input type="button" id="btn1" name="myButton" value="Click Me" />
<input type="button" id="btn2" name="myButton" value="Click Me" />
:
:
:
<input type="button" id="btn50" name="myButton" value="Click Me" />

Which is the best way to assign click event to all buttons using jQuery?

By using id or by using name attribute ?

8条回答
时光不老,我们不散
2楼-- · 2020-02-07 04:38

This would be an easy way to wrap it all up into one 'on' event and do something based on the button id;

<button id='button1'>button 1</button>
<button id='button2'>button 2</button>
<button id='button3'>button 3</button>


var mybuttons =  $('#button1');

for(i=1;i<3;i++){
    mybuttons = mybuttons.add($('#button'+i));
}
console.log(mybuttons);

mybuttons.on('click', function(){
    var myid = $(this).attr("id");
    console.log(myid);
    //use a switch or do whatever you want with the button based on the id;
});

here's a fiddle http://jsfiddle.net/gisheri/CW474/1/

查看更多
乱世女痞
3楼-- · 2020-02-07 04:39

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:

查看更多
登录 后发表回答