【问题标题】:loop not writing expected output in the dom 15 times循环未在 dom 中写入预期输出 15 次
【发布时间】:2021-11-21 19:04:57
【问题描述】:

为什么循环没有在 dom 中写入预期输出 15 次

我正在尝试与另一个 div 孩子创建一个元素 div 15 次

这里是代码


for(let i=1;i<=15;i++){
    let smalldiv=document.createElement("div").textContent=i;
    let pr =document.createElement("div");
    pr.textContent="product";
};
smalldiv.appendChild(pr);


【问题讨论】:

  • appendChild() 调用放入循环中。您只附加最后一个。
  • 您没有将smalldiv 设置为div,而是将其设置为i
  • 这段代码的最后一行应该会出错。而且你永远不会向 DOM 附加任何东西。

标签: javascript html loops for-loop dom


【解决方案1】:

首先创建 div smalldiv,然后添加 textContent。 然后,您需要使用 DOM 中已有的元素将元素附加到 DOM 或附加到 document.body。

for(let i=1;i<=15;i++){
    // create the div and assign the variable
    let smalldiv=document.createElement("div");
    // set the textContent once created
    smalldiv.textContent = `${i}. `;
    // create new div 'pr'
    let pr = document.createElement("span");
    // assign its content
    pr.textContent="product";
    // append pr to smalldiv
    smalldiv.append(pr);
    // append smalldiv to the body
    document.body.append(smalldiv);
};

【讨论】:

    【解决方案2】:
    let smalldiv=document.createElement("div").textContent=i;
    

    没有将 smalldiv 设置为 DIV。当你写

    let x = y = z;
    

    相当于

    y = z;
    let x = y;
    

    所以您将 smalldiv 设置为您分配给 itextContent

    即使您确实将 smalldiv 设置为 DIV,您也永远不会将其附加到 DOM,因此您不会看到结果。

    由于您在循环后将pr 附加到smalldiv,因此您只是附加了最后一个pr。但这也行不通,因为pr 的作用域是循环体,所以循环完成后你不能引用它。您应该将其附加到循环中。

    不要将 DIV 用于编号项目,使用有序列表 &lt;ol&gt;,其中包含 &lt;li&gt; 元素。

    let ol = document.createElement("ol");
    for(let i=1;i<=15;i++){
        let pr =document.createElement("li");
        pr.textContent="product";
        ol.appendChild(pr);
    };
    document.body.appendChild(ol);

    【讨论】:

      猜你喜欢
      • 2017-02-03
      • 2020-09-02
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多