[英]dynamic adding of checkbox and input box jquery
for (var i = 0; i < Object.keys(value.material).length; i++) {
var newRow = $('<tr/>');
newRow.append('<td ><input type="checkbox" class="" name="[]" CHECKED/>Others</td><td><input type="text" value="' + value.material + '" class="" id="' + i + '"><button class="">Delete</button></td>');
}
$("#tbl > tbody > tr:last").after(newRow);
假设我具有这种动态添加功能,如何防止第一个循环添加删除按钮。 这样做的原因是因为默认屏幕上有一行没有按钮,并且当我动态添加这些新行时,我删除了第一行。 所以我需要第一个动态添加的行没有按钮,以便它看起来像我仅添加了按钮,而我没有删除第一个。
为了防止第一行出现按钮,请检查循环中i===0
,
for (var i = 0; i < Object.keys(value.material).length; i++) {
var newRow = $('<tr/>');
if(i===0) {
newRow.append('<td ><input type="checkbox" class="" name="[]" CHECKED/>Others</td><td><input type="text" value="' + value.material + '" class="" id="' + i + '">');
} else {
newRow.append('<td ><input type="checkbox" class="" name="[]" CHECKED/>Others</td><td><input type="text" value="' + value.material + '" class="" id="' + i + '"><button class="">Delete</button></td>');
}
}
for (var i = 0; i < Object.keys(value.material).length; i++) {
var newRow = $('<tr/>');
newRow.append('<td ><input type="checkbox" class="" name="[]" CHECKED/>Others</td><td><input type="text" value="' + value.material + '" class="" id="' + i + '">' + (i == 0 ? '' : '<button class="">Delete</button></td>'));
}
$("#tbl > tbody > tr:last").after(newRow);
使用更多的jQuery吗?
$("#tbl > tbody > tr:last").after(function () {
var i = 0;
return $.map(value.material, function (val, key) {
var row = $('<tr />'),
cell1 = $('<td />'),
cell2 = $('<td />'),
inp1 = $('<input />', {
type : 'checkbox',
name : '[]',
checked : 'checked'
}),
inp2 = $('<input />', {
type : 'text',
value : val,
id : i
}),
button = $('<button />', {
text : 'Delete'
});
return row.append(
cell1.append(inp1),
cell2.append(inp2, (i++ !== 0 ? button : []))
);
});
});
尝试这个
for (var i = 0; i < Object.keys(value.material).length; i++)
{
var newRow = '<tr>';
newRow += '<td ><input type="checkbox" class="" name="[]" CHECKED/>Others</td><td><input type="text" value="' + value.material + '" class="" id="' + i + '">';
if(i != 0)
newRow += '<button class="">Delete</button>'
newRow += '</td></tr>'
}
$("#tbl > tbody > tr:last").after(newRow);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.