JQuery将事件分配给按钮 [英] JQuery assign events to buttons
问题描述
我有50个动态生成的HTML按钮,如下所示:
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" />
使用jQuery为所有按钮分配点击事件的最佳方法是什么?
Which is the best way to assign click event to all buttons using jQuery?
使用 id
或使用 name
属性?
推荐答案
事件监听器耗费内存。你必须仔细考虑如何实现听众。
Event listeners cost memory. You have to think carefully about how you should implement the listeners.
1。直截了当的方式:
不要使用
如果每个按钮的行为是相同的,使用一个类:
If the behaviour for each button is the same, use a class:
$(".btn").click(function() {
// Do something
});
如果每个按钮的行为不同,请将事件分配给不同的#ID
If behaviour for each button is different, assign events to different #IDs
$("#btn1").click(function {
// Do something
});
2。使用.on():
jQuery 1.7引入了.on()方法,它将所有侦听器包装为1个方法。
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。使用包装器(使用它!):
用div包裹你的按钮并为它创建一个监听器。
Wrap your buttons with a div and create one listener for it.
$("#wrapper").on("click", "button", function() {
// Do something
});
有用的资源:
- Performance comparison
- .on()
这篇关于JQuery将事件分配给按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!