[英]How to get id of a element in all the rows of a table using jQuery
我的表id是“termTable”。 我正在遍历表格的每一行。 文本框的id是“label'+ i +'”,因为我用循环来随机生成id。 在添加行或删除行之后,i的值将是无序的。 示例:ID为label1,label2,label3。 删除第二行后,我添加另一行。 所以现在ID是label1,label3,label4。 我想检索所有文本框元素的所有ID。 我怎样才能实现它? 请帮忙。
for (var i = 0; i < firstTabLength; i++) {
var row = $("#termTable tr").eq(i);
var id = row.find('input[type="text"]').attr('id'); // I could see id = undefined
}
这是Html。 这是为了将新行添加到表中。 猜猜你可以在下面的代码的帮助下可视化表格结构。
function AddCustomTerm1() {
len = len + 1;
var table = document.getElementById("termTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" class="form-control" id="label' + (len - 1) + '" name="label' + (len - 1) + '" value=""><input type="hidden" id="step' + (len - 1) + '" value="1"/>';
row.insertCell(1).innerHTML = '<select class="form-control" id="dataTypes' + (len - 1) + '" name="dataTypes' + (len - 1) + '" onchange="changeDataType(this)"></select>'
row.insertCell(2).innerHTML = '<input type="text" class="form-control" id="ContractTerm' + (len - 1) + '" name="ContractTerm' + (len - 1) + '" value="">';
var DD = document.getElementById("dataTypes" + (len - 1));
for (var i = 0; i < datatypesarray.length; i++) {
var opt = document.createElement("option");
opt.text = datatypesarray[i];
opt.value = datatypesarray[i];
DD.appendChild(opt);
}
没有你的HTML格式不能帮助太多。
但尝试这些。你甚至不需要一个for循环来从表中获取所有文本框及其ID。
var ids=[];
$('#termTable input[type="text"]').each(function(){
ids.push($(this).attr('id'))
})
如果你想在表格的第一列中的文本框的id。试试这个
var ids=[];
$('#termTable tr').each(function(){
ids.push($(this).find('td:first-child input[type="text"]').attr('id'))
})
最佳做法是为需要迭代的所有元素添加特定类。
例如,将class term-table-input
到输入中:
row.insertCell(0).innerHTML = '<input type="text" class="form-control term-table-input" id="label' + (len - 1) + '" name="label' + (len - 1) + '" value=""><input type="hidden" id="step' + (len - 1) + '" value="1"/>';
并迭代它们:
var termTableInputIDs = [];
$('.term-table-input').each(function () {
termTableInputIDs.push($(this).attr('id'));
});
您还可以在此处阅读有关编写高效css的更多信息: https : //developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS
由于您连续input[type="text"]
多个input[type="text"]
,因此您应该采用第一个输入。 你也可以使用each()
而不是for
。
$('#termTable tr').each(function() {
var id = $(this).find('input[type="text"]:first').attr('id');
console.log(id);
});
您可以使用$('#termTable input')
找到表中的所有输入元素,并遍历您使用$.each
API的所有选定元素
使用如下代码。
var InputIds = []; //array to hold your id's
$.each($('#termTabel input[type="text"]'),function(i,v){
InputIds.push($(this).attr('id'));
});
console.log(InputIds.toString());
//this finds all inputs which id start from "label"
$('#termTable input[id^="label"]').each(function(){ console.log(this.id); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.