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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...