我已动态生成此复选框元素,我正在尝试动态检查它。 我是这样做的:
var id = "123"; //dynamically generated
var input = document.createElement("input");
input.setAttribute("type", "checkbox");
input.setAttribute("name", "x_"+id);
input.setAttribute("id", "x_"+id);
input.setAttribute("value", "");
input.setAttribute("checked",true); //This isn't working
var elem = document.getElementById('x_' + id);
elem.checked = true; //This isn't working
答案 0 :(得分:3)
您永远不会将该元素添加到页面中。它在这里工作,只需要做:
document.body.appendChild(input);
var id = "123"
var input = document.createElement("input");
input.setAttribute("type", "checkbox");
input.setAttribute("name", "x_"+id);
input.setAttribute("id", "x_"+id);
input.setAttribute("value", "");
input.setAttribute("checked",true); //This isn't working
document.body.appendChild(input);
var elem = document.getElementById('x_' + id);
elem.checked = true; //This isn't working`enter code here`