我如何使运行此代码成为可能? [重复]

问题描述 投票:0回答:1

是否有可能在js中创建这样的动态var名称?

for (count = 10; count > 0; count--) {
    let name = "inp" + count;
    // here I want to put the value of var "name" for this...
    let name = document.createElement("input");
    // I want to make it dynamically
    // is it possible?
}
javascript for-loop input dynamic var
1个回答
-1
投票

不清楚您要问什么,但是您的代码有些错误。

  1. 不能有两个在相同作用域中被命名为相同的变量
  2. 变量将在for循环的每次迭代中重新分配。

也许您想知道是否可以创建一个动态元素并将其赋值为name变量的值,然后是。

这是一个很好的例子,来自:https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

document.body.onload = addElement;

function addElement () { 
  // create a new div element 
  var newDiv = document.createElement("div"); 
  // and give it some content 
  var newContent = document.createTextNode("Hi there and greetings!"); 
  // add the text node to the newly created div
  newDiv.appendChild(newContent);  

  // add the newly created element and its content into the DOM 
  var currentDiv = document.getElementById("div1"); 
  document.body.insertBefore(newDiv, currentDiv); 
}
© www.soinside.com 2019 - 2024. All rights reserved.