【问题标题】:document.getElementByID and for loopdocument.getElementByID 和 for 循环
【发布时间】:2015-03-09 06:39:29
【问题描述】:
<button id="mybtn">click me for index </button>

我的 JavaScript 代码:

var myarray = [2,4,6,5,5];

(i=0; i<= myarray.length; i++){

   var allBtn = document.getElementByID("mybtn");

   document.body.appendChild(allBtn);
}

我想制作多个按钮,所以我使用 for 循环来创建这些按钮。但它不起作用。

这里是网址:http://jsbin.com/donafuluha/1/edit?html,js,console,output

【问题讨论】:

  • 函数名应该是document.getElementById。 Javascript 区分大小写。
  • 请更清楚地解释您要做什么。数组中的数字是干什么用的?
  • 您的页面中只能有一个 ID。你可以有多个类名。

标签: javascript arrays button for-loop getelementbyid


【解决方案1】:

您可以使用 cloneNode 来附加现有元素

Working Demo

代码:

var myarray = [2,4,6,5,5];


for(var i=0; i< myarray.length; i++){

  var allBtn = document.getElementById("mybtn").cloneNode(true);

  document.body.appendChild(allBtn);

}

【讨论】:

【解决方案2】:

您可以使用 cloneNode() 来复制它并附加多个。我还建议您从 DOM 中删除节点并仅在屏幕上显示克隆。看着你的数组,你似乎也想附加一些数据。这可以通过分配属性或使用 .setAttribute("name",value)

来完成
var myarray = [2,4,6,5,5];
var proto = document.getElementById("mybtn");
proto.parentElement.removeChild(proto);

for(var i=0; i<myarray.length; i++){
    var allBtn = proto.cloneNode(true);
    allBtn.setAttribute("data-index", myarray[i]);
    document.body.appendChild(allBtn);
}

【讨论】:

  • 啊!按照你的评论做了。感谢宝贵的建议。 jsbin.com/xeficacoya/1/edit
  • 我也不得不问,我可以在你链接的 jsbin 中看到你没有使用数组中的值。 [2,4,6,5,5] 这些数字是什么意思?
【解决方案3】:
You should try following code snippet it will solve your problem 
    var myarray = [2,4,6,5,5];
    for(var i=0; i<= myarray.length; i++){
        var btn = document.createElement("BUTTON");
        var t = document.createTextNode("New Button"+(i+1));
        btn.appendChild(t);
        document.body.appendChild(btn);
      }

【讨论】:

  • 你为什么不直接写 btn.innerHTML = "New Button"+(i+1); ?
  • 虽然这可能会回答这个问题,但在您的答案中加入一些文字来解释您在做什么总是一个好主意。阅读how to write a good answer
猜你喜欢
  • 1970-01-01
  • 2013-03-06
  • 2019-08-28
  • 2017-11-19
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
  • 2014-03-15
  • 1970-01-01
相关资源
最近更新 更多