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:21

if you have all the buttons inside of a container and you want the same function for all add the click handler to the container

DEMO

$("#container").on("click", function(e){
    if(e.target.type =="button")
    {
        alert(e.target.id);
    }
});

<div id="container">
    <input type="button" id="test1" value="button1"/>
    <input type="button" id="test2" value="button2"/>
    <input type="button" id="test3" value="button3"/>
    <input type="button" id="test4" value="button4"/>
    <input type="button" id="test5" value="button5"/>
    <input type="button" id="test6" value="button6"/>

    something 
    <input type="text"/>
</div>
查看更多
\"骚年 ilove
3楼-- · 2020-02-07 04:24

I think it will be better if you use a common class name for all and handle click event by that class name.

$('.classname').click(function(){
    //`enter code here`
});

Or you can handle event by tag name:

$('button').click(function(){
    //'enter code here'
});

This method might effect the function of other buttons which are not included in the group of 50 buttons.

查看更多
走好不送
4楼-- · 2020-02-07 04:30

I would apply it to the parent element of the buttons. So if all of the buttons were in <div id="myButtons">:

$('#myButtons').on('click', 'button' function () {
    // Do stuff...
});

The key is to be specific enough that you do not have to specify each selector but not too lose as there may be other buttons, etc. on the page that you do not want to include.

Updated code to include delegation.

查看更多
甜甜的少女心
5楼-- · 2020-02-07 04:32

You can use following code:

 $("#btn1").on("click",function(){
      // Your code
 });

 $("#btn2").on("click",function(){
      // Your code
 });

and so on...

查看更多
我命由我不由天
6楼-- · 2020-02-07 04:33

Best way would be to delegate to the surrounding container, that way you only have one listener rather than 50. Use .on()

https://api.jquery.com/on/

If you must assign to each button, figure out a way to write only one selector, like this:

$('button').click(function(){});

Note your selector may need to be more specific to target just these 50 buttons, as @Drewness points out in the comments.

查看更多
我想做一个坏孩纸
7楼-- · 2020-02-07 04:35

Try

$(".btn").click(function() {
    // Do something
});
查看更多
登录 后发表回答