问题设置复选框用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);