javascript - 在 IF 语句中使用 jQuery 创建元素时出现类型错误?

标签 javascript jquery

我正在根据变量值动态创建具有不同属性的输入元素。如果没有 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/

相关文章:

javascript - 我不断收到 NaN,但我不知道如何解决它

javascript - 动态添加 html 表单元素和更新的数据被重置

javascript - PHP选择输入日历?

jquery - Yii 2 GridView访问当前行及其列内容并通过ajax更新行

javascript - 使用greasemonkey重定向到域中的页面

javascript - window.scrollBy 在 Chrome 和 Safari 中的散列/ anchor 滚动之前触发

javascript - 对话流中 request 和 Cheerio 的问题

javascript - 自动填充选项消失或无明显原因重新出现

javascript - 如何防止按键事件出现警报框后重新加载页面?

javascript - 在没有 jquery 的情况下使用 javascript 淡入