javascript - 使用 for 循环附加子元素,如果 i%3 ==0 我想在该数字的输入后添加一个 <br>

标签 javascript

let buttonArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
for (let i of buttonArr) {
  let numberButton = document.createElement("input");
  numberButton.type = "button";
  numberButton.value = i;
  document.body.appendChild(numberButton);


  if (i % 3 == 0) {
    let breakMark = document.createElement("br");
    document.body.appendChild("breakMark");
  } else {
    console.log(i);
  }
}

我想使用appendChild()在 JavaScript 中,使用 for 循环根据数组的长度将输入标记添加到 HTML。我只想在一行中显示三个按钮,这意味着在将三个新输入标记添加到 HTML 后,我想添加一个
元素。我的想法是如果i%3 == 0然后appendChild() <br>到 HTML 但它看起来是错误的。

非常感谢任何帮助。

最佳答案

Node.appendChild()

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

通过用引号将 breakMark 括起来,您将附加字符串文字而不是变量(它是一个节点)的值。但由于 Node.appendChild() 添加节点而不是 DOMString,因此会抛出错误:

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'."

因此删除周围的引号,以便 appendChild() 将创建的节点作为参数:

let buttonArr = [1,2,3,4,5,6,7,8,9,0];
for(let i of buttonArr){
  let numberButton = document.createElement("input");
  numberButton.type = "button";
  numberButton.value = i;
  document.body.appendChild(numberButton); 


  if(i%3 == 0){
      let breakMark = document.createElement("br");
      document.body.appendChild(breakMark); //remove the quotes
  }else{
      console.log(i);
  }
}

关于javascript - 使用 for 循环附加子元素,如果 i%3 ==0 我想在该数字的输入后添加一个 <br>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53029140/

相关文章:

javascript - 类型 'controls' 上不存在属性 'AbstractControl'。在 Angular 8

javascript - 如何在ajax响应中的多个函数上使用回调

javascript - 如何向 onclick 事件添加唯一 id

javascript - Juniper SSL VPN 中的 Angular Web 应用程序路由

javascript - 如何在不改变时间的情况下将 Date 对象转换为 UTC?

javascript - $getScript 加载 google maps api 的方法 -> 空白页面?

javascript - 如何使用字符串访问对象的嵌套属性?

javascript - 用于 SEO 的 Data Bound JS 预加载数据

javascript - 具有相同类的对象有时不会隐藏

javascript - XMLHttpRequest 响应XML 始终为 null