javascript - 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>
为什么这不起作用?
解决方案
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>
推荐阅读
- python - 有没有办法在 TextFSM 的状态更改中继续使用同一行?
- javascript - 从 Google App 脚本发送电子邮件时出错
- html - SCSS(或 CSS)布局,带有动态高度标题和下面的主要内容
- python - 需要使用 matplotlib 在数据框的折线图上标记随时间变化的百分比
- python-3.x - 在 Python 中使用 BeautifulSoup 提取“a”标签时的空变量
- javascript - HTML 页脚导航按钮
- git - Git 两个起源,从一个拉到另一个
- apache-spark - 如何刷新 HDFS 路径?
- html - 将 ID 传递到 Bootstrap 删除模式
- javascript - 使用 Joi 进行无对象验证