javascript: 动态更改名称属性

javascript: changing the name attribute dynamically

我有这个正在处理的脚本,上面没有错误,但我想在上面添加一些功能,就像当我单击它添加的按钮时一样,但我想更改输入文本的名称属性也是。

这是我的脚本:

javascript:

var a = 1;
function add() {

    var fContent = document.getElementById('1');
    var sContent = document.getElementById('2');
    if (a <= 10) {
        a++;
        var objTo = document.getElementById('m');
        var divtest = document.createElement("div");
        divtest.innerHTML = (sContent.innerHTML + a + fContent.innerHTML);
        alert(divtest.innerHTML); 
        objTo.appendChild(divtest);
    }
}

html:

<input type="button" onclick="add();" value="+" />
<div id="m">
<div id="1">
<input type="text" name="f">
<input type="text" name="l">
<input type="text" name="m">
</div>
<div id="2"></div>
</div>

OUTPUT:

2
<input type="text" name="f">
<input type="text" name="l">
<input type="text" name="m">

EXPECTED OUTPUT:

2
<input type="text" name="f2">
<input type="text" name="l2">
<input type="text" name="m2">

等等...

您没有做任何更改名称属性的事情。尝试使用 html 连接进行这些更改会给您带来麻烦。这将帮助您入门:

(function() {

  var a = 1;

  // get a reference to the container
  var container = document.getElementById("m");
  // get a reference to the first row of input
  var base = container.children[0];  
  
  document.querySelector("button").addEventListener("click", function(e) {

    if(++a > 10) return;
    
    // clone the first row of input
    var clone = base.cloneNode(1);
    
    // change the number text by setting the span's textContent
    clone.children[0].textContent = a;
    // set the names of the input fields
    clone.children[1].name = "f" + a;
    clone.children[2].name = "l" + a;
    clone.children[3].name = "m" + a;
    
    // add the new row to the container
    container.appendChild(clone);
    
    console.log(clone);

  });

})();
<button type="button">+</button>
<div id="m">
  <div><span>1</span><input type="text" name="f1"><input type="text" name="l1"><input type="text" name="m1"></div>
</div>

如果您更愿意从头开始创建元素...

(function() {

  var a = 1;

  // get a reference to the container
  var container = document.getElementById("m");    
  var input;
  var span;
  var div;
  
  document.querySelector("button").addEventListener("click", function(e) {

    if(++a > 10) return;
    
    // create our div
    div = document.createElement("div");
    
    // create and append our span
    span = document.createElement("span");
    span.textContent = a;
    div.appendChild(span);
    
    // create and append inputs    
    ["f","l","m"].forEach(function(n){
       input = document.createElement("input");
       input.name = n + a;
       div.appendChild(input);            
    });
                
    // append our div
    container.appendChild(div);
    
    console.log(div);

  });

})();
<button type="button">+</button>
<div id="m">
  <div><span>1</span><input type="text" name="f1"><input type="text" name="l1"><input type="text" name="m1"></div>
</div>