我目前有两个按钮。我想单击一个按钮时,两个按钮都被禁用。我只想使用没有jQuery的javascript。
var button1=document.getElementById("button1").addEventListener('click',function(){
//I want to check if either of the buttons were clicked and disable both of them.//
if(button1||button2===true){
button1.disable=true;
button2.disable=true;
Alert("Button Disable property is in a true state.");
}
});
var button2=document.getElementById("button2").addEventListener('click',function(){
//I want to check if either of the buttons were clicked and disable both of them.//
if(button1||button2===true){
button1.disable=true;
button2.disable=true;
Alert("Button Disable property is in a true state.");
}
});
//I also tried to set the {once : true;} at the end of the event handler but it only works for one button.Which means that I have to press both of them tfor them both to disable.//
<button id="button1">Button1</button>
<button id="button2">button2</button>
答案 0 :(得分:2)
您遇到许多问题。首先,将变量设置为addEventListener
的返回值,而不是文档元素。其次,要禁用元素,请使用element.disabled = true
,而不要使用element.disable = true
。最后,alert
都是小写,而不是Alert
。还可以对您的代码进行优化-例如,无需检查是否单击了button1或2,因为如果调用了事件侦听器,则必须已单击其中之一。尝试以下方法:
var button1=document.getElementById("button1");
var button2=document.getElementById("button2");
[button1,button2].map(b => b.addEventListener('click',function(){
button1.disabled=true;
button2.disabled=true;
alert("Button Disable property is in a true state.");
}));
<button id="button1">Button1</button>
<button id="button2">button2</button>