Javascript使用" classList"更改按钮类。

时间:2016-06-16 14:03:14

标签: javascript html

我想在点击其中任何一个按钮时更改两个按钮的外观。但我似乎无法做到这一点。

我希望每次单击一个新按钮时都会更改按钮的类,但此代码不会发生任何变化。可能是什么问题?

function offbutton() {
    var offbtn = document.getElementById("btndisable3");
    var onbtn = document.getElementById("btnenable3");

    offbtn.classList.remove("btn btn-default");
    offbtn.classList.add("btn btn-danger active");
    onbtn.classList.remove("btn btn-success active");
  onbtn.classList.add("btn btn-default");
}

function onbutton() {
    var offbtn = document.getElementById("btndisable3");
    var onbtn = document.getElementById("btnenable3");

    onbtn.classList.remove("btn btn-default");
    onbtn.classList.add("btn btn-success active");
    offbtn.classList.remove("btn btn-danger active");
    offbtn.classList.add("btn btn-default");
}
<div class="form-group">
  <label class="col-sm-2 control-label">
    <?=$ name ?>
  </label>
  <div class="col-sm-10">
    <div class="btn-group" data-toggle="buttons">
      <label id="btndisable<?= $id ?>" class="btn <?php if($value == 0){ echo 'btn-danger active'; } else{ echo 'btn-default'; } ?>" onclick="offbutton();">
        <div class="col-sm-2">
          <input type="radio" name="options<?= $id ?>" id="disable<?= $id ?>" value="0" <?php if($value==0 ){ echo 'checked'; } ?>> O
        </div>
      </label>
      <label id="btnenable<?= $id ?>" class="btn <?php if($value == 1){ echo 'btn-success active'; } else{ echo 'btn-default'; } ?>" onclick="onbutton();">
        <div class="col-sm-2">
          <input type="radio" name="options<?= $id ?>" id="enable<?= $id ?>" value="1" <?php if($value=='1' ){ echo 'checked'; } ?>> I
        </div>
      </label>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:3)

如果要添加/删除多个类,则必须使用逗号,分隔符,以便代码应该是:

function offbutton() {
    var offbtn = document.getElementById("btndisable3");
    var onbtn = document.getElementById("btnenable3");

    offbtn.classList.remove("btn","btn-default");
    offbtn.classList.add("btn","btn-danger","active");
    onbtn.classList.remove("btn","btn-success","active");
    onbtn.classList.add("btn","btn-default");
}

function onbutton() {
    var offbtn = document.getElementById("btndisable3");
    var onbtn = document.getElementById("btnenable3");

    onbtn.classList.remove("btn","btn-default");
    onbtn.classList.add("btn","btn-success","active");
    offbtn.classList.remove("btn","btn-danger","active");
    offbtn.classList.add("btn","btn-default");
}

希望这有帮助。