如何解决问题设置复选框用JavaScript检查
我来找你是因为我在使用javascript设置checked属性时遇到问题。我用createlement创建此复选框,并将其放在li标记内。
var item = response.Result[i];
var checkboxId = "chk_modulePermission_" + item.Position;
var li = document.createElement("LI");
li.classList.add("list-group-item");
li.classList.add("form-check");
var checkbox = document.createElement("input");
checkbox.setAttribute("type","checkbox");
checkbox.setAttribute("id",checkboxId);
checkbox.setAttribute("name","modulePermissions");
checkbox.value = item.Position;
checkbox.classList.add("permission-item");
var label = document.createElement("label");
label.setAttribute("for",checboxId);
label.classList.add("form-check-label");
label.innerText = " "+item.ESTextDisplay;
li.appendChild(checkbox);
li.appendChild(label);
accessGroupList.appendChild(li);
稍后我想将其设置为选中状态,并使用以下代码,但是当我想使用getElementById获取它时,它返回null,这两个函数的Id属性都匹配
moduleIdSelect.dispatchEvent(new Event('change'));
profiles.getProfiles(fieldId).then(function (response) {
if (response === null) return;
for (var i in response.Result) {
var permission = response.Result[i]==="true";
//console.log("permission: " + permission);
if (permission === true) {
var checkboxId = "chk_modulePermission_" + i;
console.log("checkboxId: " + checkboxId);
var element = document.getElementById(checkboxId);
element.setAttribute("checked",true);
}
}
});
在“ element.setAttribute(“ checked”,true);“行中出现以下错误:
Uncaught (in promise) TypeError: Cannot read property 'setAttribute' of null at ....
我认为这是正确的,但我不知道会发生什么。
你能帮我吗?非常感谢。
解决方法
如果element
为空,则调用element.setAttribute( ... )
将触发您看到的错误。我的猜测是document.getElementById(checkboxId);
找不到该元素,因此随后的行炸了。
// if there's no element with id=checkboxId,element will be null
var element = document.getElementById(checkboxId);
// …and this will blow up
element.setAttribute("checked",true);
// because it's effectively
null.setAttribute("checked",true);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。