首页 > 解决方案 > Javascript更改内部HTML

问题描述

我想根据复选框的状态更改标签的值

function private() {
  var checkBox = document.getElementById("private");// Get the checkbox
  var text = document.querySelector('label[for="private"]');// Get the output text

  if (checkBox.checked == true)
  {
    text.innerHTML = "Public";
  } else {
    text.innerHTML = "Private";
  }
}
<label class="switch">
  <input id="private" type="checkbox" onclick="private()" />
  <span class="slider"></span>
</label>
<label for="private"></label>

为什么这不起作用?

标签: javascripthtmlfunctioninnerhtml

解决方案


querySelectorAll返回一个节点列表,因此您需要指定所需的元素,例如:

function private() {
  var checkBox = document.getElementById("private");// Get the checkbox
  var text = document.querySelectorAll('label[for="private"]')[0];// Get the output text

  if (checkBox.checked == true)
  {
    text.innerHTML = "Public";
  } else {
    text.innerHTML = "Private";
  }
}
<label class="switch">
  <input id="private" type="checkbox" onclick="private()" />
  <span class="slider"></span>
</label>
<label for="private"></label>

或者也许只是使用querySelector它只返回第一个匹配:

function private() {
  var checkBox = document.getElementById("private");// Get the checkbox
  var text = document.querySelector('label[for="private"]');// Get the output text

  if (checkBox.checked == true)
  {
    text.innerHTML = "Public";
  } else {
    text.innerHTML = "Private";
  }
}
<label class="switch">
  <input id="private" type="checkbox" onclick="private()" />
  <span class="slider"></span>
</label>
<label for="private"></label>


推荐阅读