禁用/启用按钮的JavaScript函数()

时间:2018-03-31 14:13:35

标签: javascript function button disabled-input

我的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;
}

2 个答案:

答案 0 :(得分:2)

你的功能名称有问题:你的html中的switchButton()和js中的切换器,id也不同,启用不是html属性。只需一个功能即可实现您想要的功能:

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:2)

你应该尽量避免让这个重复的逻辑变得相同,很难维护,我建议你改为使用它:

&#13;
&#13;
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;
&#13;
&#13;