這是我的html代碼:
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="mySwitch" name="emp">
<label class="form-check-label" for="mySwitch">EmpName</label>
</div>
這是我的js:
var Switch = document.getElementById("mySwitch");
Switch.addEventListener("click",function(){
if(Switch.value=="yes")
Switch.innerHTML="EmpNo";
else
Switch.innerHTML="EmpName";
})
我不知道為什么文本沒有改變。你能幫我么?
uj5u.com熱心網友回復:
您正在選擇<input>元素,但包含文本的<label>元素是輸入旁邊的元素。
const input = document.getElementById("mySwitch");
const label = input.nextElementSibling.
change在input而不是單擊上偵聽事件。只要檢查輸入或未選中,都會觸發更改事件,并且對于這種情況更可靠。
然后檢查.checked輸入上的屬性以查看復選框是否已選中。不是修改.innerHTML屬性,而是.textContent用于設定更改的文本。
input.addEventListener('change' function() {
if (input.checked) {
label.textContent = 'EmpNo';
} else {
label.textContent = 'EmpName';
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/396699.html
