如果按下四个按钮中的一个,JavaScript将执行某些操作
所以,我正在从事一个JavaScript项目,现在我需要找到一种方法,如果我按下四个按钮中的一个,它如何执行if命令。代码基本上如下所示:如果按下四个按钮中的一个,JavaScript将执行某些操作,javascript,jquery,Javascript,Jquery,所以,我正在从事一个JavaScript项目,现在我需要找到一种方法,如果我按下四个按钮中的一个,它如何执行if命令。代码基本上如下所示: i=1 if(i==1){ [[...]] $("#button1").click(function() { i++ } } if(i==2) { [[..]] } 我以为JavaScript会检查if(I==2),看,I是2并执行操作,但它没有 此解决方案使用jquery(我注意到您已经在使用它) 您需要能够唯一地标识单个按钮,如
i=1
if(i==1){
[[...]]
$("#button1").click(function() {
i++
}
}
if(i==2) {
[[..]]
}
我以为JavaScript会检查if(I==2),看,I是2并执行操作,但它没有 此解决方案使用jquery(我注意到您已经在使用它)
您需要能够唯一地标识单个按钮,如果使用索引为每个按钮添加属性,则这是可能的
拥有此唯一标识属性后,您可以使用以下行为各个按钮创建单击事件:$(“按钮[btn ind='2'])代码>。或者,您可以为任何按钮应用常规单击事件,并通过检查属性(即$(this).attr(“btn ind”)
来区分该单击事件
- 按钮1和2在下面的代码中有自己的单击事件
- 按钮3和4仅通过常规
按钮
选择器具有单击事件
如果这不是你想要的,请告诉我
$(“按钮[btn ind='1')。单击(函数(){
console.log($(this.text()+“单击”);
});
$(“按钮[btn ind='2')。单击(函数(){
console.log($(this.text()+“单击”);
});
$(“按钮”)。单击(函数(){
如果($(this).attr(“btn ind”)=“3”){
console.log($(this.text()+“单击”);
}else if($(this).attr(“btn ind”)=“4”){
console.log($(this.text()+“单击”);
}
});
按钮1
按钮2
按钮3
按钮4
我认为您弄错了基本事件模式。您试图使用简单的程序编程来区分按下的按钮,但这根本没有意义
您应该为每个按钮附加一个不同的事件处理程序,然后简单地执行该按钮应该执行的操作:
<button type="button" id="button1">1</button>
<button type="button" id="button2">2</button>
<button type="button" id="button3">3</button>
<button type="button" id="button4">4</button>
<script>
$("#button1").on("click", () => {
// button 1 was pressed, do what you must
};
$("#button2").on("click", () => {
// button 2 was pressed, do what you must
};
$("#button3").on("click", () => {
// button 3 was pressed, do what you must
};
$("#button4").on("click", () => {
// button 4 was pressed, do what you must
};
</script>
您可以使用带有不同按钮的开关盒,并从中调用不同的功能
$('button')。在('click',函数(){
var i=0;
开关($(this.attr('id')){
案例“btn1”:i+=1;中断;
情况“btn2”:i+=2;断裂;
案例“btn3”:i+=3;中断;
案例“btn4”:i+=4;中断;
}
控制台日志(i);
});
1.
2.
3.
4
欢迎!为了提出一个更好的问题,请仔细研究一下,这样我们可以更好地帮助您。如果(i==2)
条件只有在运行时i
将为2
时才会执行。在您的情况下,i=1
。您可以为每个按钮添加标识符,这些按钮还应具有单击事件处理程序。因此,当单击特定按钮时,您可以执行任何需要的操作。
<button type="button" data-command="start">1</button>
<button type="button" data-command="faster">2</button>
<button type="button" data-command="slower">3</button>
<button type="button" data-command="stop">4</button>
<script>
// attach event to all buttons with a data-command attribute
$("button[data-command]").on("click", () => {
// distinguish by data-command attribute
switch ($(this).data("command"))
{
case "start":
// perform the "start" action
break;
case "faster":
// perform the "faster" action
break;
case "slower":
// perform the "slower" action
break;
case "stop":
// perform the "stop" action
break;
default:
throw "unrecognized command (was \"" + $(this).data("command") + "\")";
}
};
</script>