我想做这样的事情:
elementX.setAttribute('checked', true); // this is input type checkbox
elementY.appendChild(elementX);
渲染和其他事情一切正常,但在页面上,未检查输入。 当我查看 chrome 控制台中的元素时,我可以看到:
<input type="checkbox" checked="true">
我该怎么办?
我已经试过了
elementX.setAttribute('checked', true);
elementX.setAttribute('checked', 'true');
elementX.setAttribute('checked', 'checked');
我在控制台中没有任何错误。
最佳答案
参见 MDN :
checked
A Boolean attribute indicating whether or not this checkbox is checked by default (when the page loads). It does not indicate whether this checkbox is currently checked: if the checkbox’s state is changed, this content attribute does not reflect the change. (Only the HTMLInputElement’s checked IDL attribute is updated.).
虽然设置 checked
属性会显示元素序列化的变化,但实际上不会选中复选框。为此,您必须调用 setter ,例如
elementX.checked = true;
关于javascript - 为什么 element.setAttribute ('checked' , true) 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57617532/