JavaScript 输入标签未设置 ID 或类

javascript input tag not setting id or class

本文关键字:ID 或类 设置 输入 标签 JavaScript      更新时间:2023-09-26

我有一个表,其中包含从MySql查询创建的输入行。 用户可以更改这些行,但他/她可能还希望添加新行。 所以我创建了一个 javascript 函数,以便在单击按钮时添加一个新行。 新行正在正确创建,但输入标记未获取其 id 或类。

  function addrow(id) {
  var tableref = document.getElementById(id);
  var nextseq  = document.getElementById('maxseq').value;
  var newRow = tableref.insertRow(2);
  var rowid  = "tr"+nextseq;
//first cell
 var cell1 = newRow.insertCell(0) ;
 var text1 = document.createTextNode(nextseq);
 cell1.appendChild(text1);
 var id1   = "cell" + nextseq + "1"; 
 cell1.id = id1;
//second cell
var id2   = "cell" + nextseq + "2";             
var cell2 = newRow.insertCell(1).innerHTML = '<input type = "text" id = id2 class = "xxx"    style = "width:100px" value = "1001-01-01" >';
//  var test = document.getElementById(id2);
//alert("test is " + test); 

    ...more stuff which is working fine ...
 }
">

test"上的警报给出"test is null",所以我收集了 id 未被设置。

我也试过

var abc = document.getElementsByClassName("xxx");
alert("abc is " + abc); 

并且警报显示 abc 是 [对象 HTMLCollection]

如何解决此问题以使 id 和类正常工作?

由于 id2 是一个变量,你应该这样使用。

 var cell2 = newRow.insertCell(1).innerHTML = '<input type = "text" id =' + id2 + 'class = "xxx"    style = "width:100px" value = "1001-01-01" >';
您需要

将变量连接成字符串。JS没有字符串插值。

var id2   = "cell" + nextseq + "2";             
var cell2 = newRow.insertCell(1).innerHTML = '<input type = "text" id = ' + id2 + ' class = "xxx"    style = "width:100px" value = "1001-01-01" >';

但请注意,cell2保存字符串,而不是新节点。一个更好的方法来做到这一点 IMO 是这样的:

var cell2 = newRow.insertCell(1);
var input = cell2.appendChild(document.createElement('input'));
input.id = "cell" + nextseq + "2"; 
input.className = "xxx";
input.value = "1001-01-01";

然后,我将width:100px;样式信息放在CSS中而不是元素上。但如果它必须在那里,那么:

input.style.width = "100px";

alert()给了[HTMLCollection],因为这是从getElementsByClassName()返回的内容。不确定您要查找的输出。