gpt4 book ai didi

Javascript jQuery 多个按钮和点击事件

转载 作者:行者123 更新时间:2023-11-30 09:30:50 24 4
gpt4 key购买 nike

我正在把有很多按钮的东西放在一起,每个按钮做不同的事情。

我的做法是这样的:

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

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

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

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

...等等...

我的问题是...

有没有更好的方法来做到这一点,例如,有一个带有按钮 ID 的数组,并在点击事件后调用此函数?

最佳答案

如果您将按钮及其相应的 click 回调函数存储在数组/对象结构中,您可以压缩它,然后制作一个通用函数以在正确的时间调用每个:

$( "button" ).click(function(evt) { 
// this binding is lost inside of forEach
var id = this.id;
// Loop over each stored object in the array...
var result = buttonsAndFunctions.forEach(function(obj){
// If the current object.button matches the button.id, invoke the function
// Since the function won't directly recieve the event, we'll pass the event
// to the function:
(obj.button === id) ? obj.fn(evt) : "";
});
});


var buttonsAndFunctions = [
// I'm using the same function for each button here only for demonstration
// In reality, they'd each be different
{ button : "btn1", fn : function(evt){ console.log(evt.target.id + " was clicked"); } },
{ button : "btn2", fn : function(evt){ console.log(evt.target.id + " was clicked"); } },
{ button : "btn3", fn : function(evt){ console.log(evt.target.id + " was clicked"); } },
{ button : "btn4", fn : function(evt){ console.log(evt.target.id + " was clicked"); } }
]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>
<button id="btn3">Button 3</button>
<button id="btn4">Button 3</button>

关于Javascript jQuery 多个按钮和点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46383928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com