我正在根据变量值动态创建具有不同属性的输入元素。如果没有 IF 语句,以下几行可以完美运行:
$("<input />")
.attr("id", "input" + i)
.attr("type", "checkbox")
.attr("class", "inline checkbox")
.attr("checked")
.attr("data-role", "none")
.appendTo("#input" + i + "container");
但是,当我使用以下命令时,出现此错误:
TypeError: $(...).attr(...).attr(...).attr(...).attr(...) is undefined
var checked = localStorage.getItem(i + "checked");
if (checked === "true") {
$("<input />")
.attr("id", "input" + i)
.attr("type", "checkbox")
.attr("class", "inline checkbox")
.attr("checked")
.attr("data-role", "none")
.appendTo("#input" + i + "container");
} else {
$("<input />")
.attr("id", "input" + i)
.attr("type", "checkbox")
.attr("class", "inline checkbox")
.attr("data-role", "none")
.appendTo("#input" + i + "container");
}
最佳答案
因为 .attr("checked")
返回一个 bool 值,因此它会破坏您的链接。您忘记添加它的值部分。
您可以使用一个对象在一次调用中添加多个属性
$("<input>")
.attr({
"id": "input" + i,
"type": "checkbox",
"class", "inline checkbox"
});
对于 jQuery 1.6,你确实应该使用 prop() 来设置选中状态。
$("<input>")
.attr({})
.prop("checked", true) //.prop("checked", false)
关于javascript - 在 IF 语句中使用 jQuery 创建元素时出现类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43668693/