我正在制作一个计数按钮,但问题是因为我重复相同的代码至少 100 次,这使得代码变得巨大,有没有办法不对不同的按钮重复数百次?
$('#rcleric21').click( function() {
counter11 = $('#rankcleric11').val();
if (counter11 > 0) {
counter11--;
total[3]++;
totalranktres--;
$('#rankcleric11').val(counter11);
$('.skillpoints3').val(total[3]);
}
});
$('#rcleric22').click( function() {
counter11 = $('#rankcleric11').val();
if (counter11 < 5 && totalranktres <15){
counter11++ ;
total[3]--;
totalranktres++;
$('#rankcleric11').val(counter11);
$('.skillpoints3').val(total[3]);
}
});
最佳答案
您可以创建一个函数,例如
function doSomething(e) {
console.log('Do Something');
}
$('#someId').click(doSomething);
$('#someId2').click(doSomething);
这样您就无需重复在单击回调(doSomething 函数)中执行的代码。显然,您应该调整内部代码以使其更加通用,因此它可以根据情况执行您需要的任何操作(选择器可能会更改,等等)。
如果您需要对很多元素执行此操作,应考虑向其添加一个类(无需循环遍历所有元素来附加回调)。
你的代码应该看起来像..
function doSomething(e) {
var elem = $(e.currentTarget);
console.log(elem);
//Apply your logic here based on the element here.
}
$('.clickToDoSomething').click(doSomething);
关于javascript - 有没有办法不重复这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32334857/