使用全局变量为动态创建的元素分配唯一ID和唯一名称

时间:2013-06-13 23:22:02

标签: javascript dom-manipulation

我尝试了不同的方法为动态创建的input字段分配唯一的名称,以便我可以在PHP中访问它们的值。我们知道可以在JavaScript中声明一个全局变量,这意味着每次在单击按钮时调用addRow()函数时,变量的值都不会重新初始化,因此我可以将其用作索引对于名称或ID,但我无法使其执行。

var count = 2;

function addRow() {

  var table=document.getElementById("studenttable");
  var row=table.insertRow(-1);

  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);  

  cell1.innerHTML="<td> <input type='text' **name='nametext+count'" +
    "id='nametext+count'** required  >"; 

  /* also tried..  
  cell1.innerHTML="<td> <input type='text' name='nametext"+count" '" +
    "id='nametext"+count "' required>";
  */

  cell2.innerHTML="<td><div class='dropdown dropdown-dark'>" +
    "<select name='two' class='dropdown-select' >" +
    "<option value=''>Select an option</option><div>" +
    "<option value='1'>Male</option>" +
    "<option value='2'>Female</option></div>" +
    "</option></select></div></td>";

  count++;
}

2 个答案:

答案 0 :(得分:0)

变化:

cell1.innerHTML="<td> <input type='text' name='nametext+count' id='nametext+count' required  >"; 

要:

cell1.innerHTML="<td> <input type='text' name='" + nametext+count + "' id='" + nametext+count + "' required  >";

不会在JavaScript中解释字符串文字。

答案 1 :(得分:0)

您的代码适用于input(不适用于select),但我会建议整体更清晰,更不容易出错,不同的方法。它以正确的方式创建节点(使用document.createElement())而不是设置innerHTML - 避免转义错误,无效的HTML标记和其他常见错误

<强> Click here for demo

var count = 2;

function addRow() {

    var table = document.getElementById("studenttable");
    var row = table.insertRow(-1);

    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);

    var ipt = document.createElement('input');
    ipt.setAttribute("type", "text");
    ipt.name = "nametext" + count;      // setting unique NAME
    ipt.id = "nametext" + count;        // setting unique ID
    ipt.setAttribute("required", "true");

    cell1.appendChild(ipt);

    var theDiv = document.createElement('div');
    theDiv.setAttribute("class", "dropdown dropdown-dark");
    var theSelect = document.createElement('select');

    theSelect.name = "select"+count;  // setting unique NAME
    theSelect.id = "select"+count;    // setting unique ID

    theSelect.setAttribute("class", "dropdown-select");
    // option "Select an option"
    var opt0 = document.createElement('option');
    opt0.value = "";
    opt0.text = "Select an option";
    theSelect.appendChild(opt0);
    // option "Male"
    var opt1 = document.createElement('option');
    opt1.value = "1";
    opt1.text = "Male";
    theSelect.appendChild(opt1);
    // option "Female"
    var opt2 = document.createElement('option');
    opt2.value = "2";
    opt2.text = "Female";
    theSelect.appendChild(opt2); 

    theDiv.appendChild(theSelect);
    cell2.appendChild(theDiv);

    count++;
}