我的HTML中有两个按钮:
<form>
<input type="button" id="button1" value="Clickable" onClick="switchButton()">
<input type="button" id="button2" value="Not Clickable" onClick="switchButton2()" disabled="true">
</form>
我想在JavaScript中编写一个函数(),当我点击button1时,它应该被禁用并将其值更改为“not clickable”,并且应该启用button2并将其值更改为“clickable”,反之亦然
我写了两个函数,但它们不正确,我对JavaScript很新。这是我的函数():
function switcher() {
var btn = document.getElementById("knapp1");
btn.disabled = true;
}
function switcher2(){
var btn2 = document.getElementById("knapp2");
btn2.enabled = true;
}
答案 0 :(得分:2)
你的功能名称有问题:你的html中的switchButton()和js中的切换器,id也不同,启用不是html属性。只需一个功能即可实现您想要的功能:
function switchButton(btn1, btn2) {
var btn1 = document.getElementById("button"+btn1);
var btn2 = document.getElementById("button"+btn2);
btn1.disabled = true;
btn1.value = "not clickable";
btn2.disabled = false;
btn2.value = "clickable";
}
&#13;
<form>
<input type="button" id="button1" value="Clickable" onClick="switchButton(1,2)">
<input type="button" id="button2" value="Not Clickable" onClick="switchButton(2,1)" disabled="true">
</form>
&#13;
答案 1 :(得分:2)
你应该尽量避免让这个重复的逻辑变得相同,很难维护,我建议你改为使用它:
function clickButton(e) {
const currentBtn = document.getElementById(e);
const otherBtn = document.getElementById(e === "knapp2"? "knapp1": "knapp2");
currentBtn.disabled = true;
otherBtn.disabled = false;
currentBtn.value="Not Clickable"
otherBtn.value="Clickable"
}
&#13;
<form>
<input type="button" id="knapp1" value="Clickable" onClick="clickButton('knapp1')">
<input type="button" id="knapp2" value="Not Clickable" onClick="clickButton('knapp2')" disabled>
</form>
&#13;