gpt4 book ai didi

javascript - 无法在复选框上输入 addEventListener?

转载 作者:行者123 更新时间:2023-11-27 23:11:58 24 4
gpt4 key购买 nike

db-kepala-ruangan.js

 var checkbox = document.getElementsByName('checkbox');
var dragon = document.createElement("label");
dragon.innerHTML = "imam";
for(var i = 0; i < checkbox.length; i++){
checkbox[i].addEventListener("change", checkedOrNot)
}

function checkedOrNot() {
var isChecked = this.checked;

if (isChecked) { //checked
console.log('checked');
} else { //unchecked
console.log('unchecked');
}
}

我正在为这些东西使用 materialize 和 cloud firestore。

这是完整的元素 https://github.com/imamdtechnolife/simpelkes

最佳答案

要为所有复选框添加事件监听器,您必须获取名称为 input 的所有标签,并将事件监听器仅添加到类型为 checkbox 的标签。

var inputList = document.getElementsByTagName('input');

for(var i = 0; i < inputList.length; i++){
if(inputList[i].type == "checkbox") {
inputList[i].addEventListener("change", checkedOrNot)
}
}

function checkedOrNot() {
var isChecked = this.checked;

if (isChecked) { //checked
console.log('checked');
} else { //unchecked
console.log('unchecked');
}
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>


<form action="#">
<p>
<label>
<input type="checkbox" />
<span>Red</span>
</label>
</p>
<p>
<label>
<input type="checkbox" checked="checked" />
<span>Yellow</span>
</label>
</p>
<p>
<label>
<input type="checkbox" class="filled-in" checked="checked" />
<span>Filled in</span>
</label>
</p>
<p>
<label>
<input id="indeterminate-checkbox" type="checkbox" />
<span>Indeterminate Style</span>
</label>
</p>
<p>
<label>
<input type="checkbox" checked="checked" disabled="disabled" />
<span>Green</span>
</label>
</p>
<p>
<label>
<input type="checkbox" disabled="disabled" />
<span>Brown</span>
</label>
</p>
</form>

关于javascript - 无法在复选框上输入 addEventListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58471758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com