[英]Dynamically add td and tr onclick HTML JQUERY
I have a table with a row and two TDs 我有一个有一行和两个TD的表
<table id="tbTest">
<tr>
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
</tr>
</table>
I also have a button that adds a new row with a td dynamically. 我还有一个按钮,动态地添加一个带有td的新行。 If the second time is clicked I want to add a second td.
如果第二次点击我想添加第二个td。 if the third time is clicked I want to add a new tr with one td...etc
如果第三次点击我想添加一个新的tr与一个td ...等
jquery on click 单击jquery
var counter = 2;
if ((counter % 2) == 0) {
row = $('<tr><td><input type="text"/></td></tr>');
}
else {
//???????????????
}
row.appendTo('#tbTest');
counter++;
I can add a tr and td (first time clicked) but the second time clicked how do I insert a second td in a tr... suggestions? 我可以添加一个tr和td(第一次点击)但第二次点击我如何在tr ...建议中插入第二个td?
thanks, 谢谢,
From your question, I guess what you want to achieve is to add a new row with table data when the button is first clicked and every other odd time (third time, fifth time etc) and to add a new table data to the created row when the button is clicked a second time and every other even time (fourth time, sixth time etc) 从你的问题来看,我想你要实现的是在第一次点击按钮时添加一个包含表数据的新行,每隔一个奇数时间(第三次,第五次等)添加新行,并将新表数据添加到创建的行当按钮被点击第二次,每隔一次甚至是时间(第四次,第六次等)
var counter = 0,
row;
$('button').click(function() {
counter++; //increase value of counter
//for every odd time click
if (counter % 2 != 0) {
row = $('<tr><td><input type="text"></td></tr>'); //create row
$('#tbTest').append(row);
}
else {
//create a table data
var tableData = $('<td><input type="text"></td>');
row.append(tableData); //append the table data to the last created row
}
});
Here is a working fiddle: http://jsfiddle.net/976PT/ 这是一个工作小提琴: http : //jsfiddle.net/976PT/
Something like this would work: 像这样的东西会起作用:
var container = $('#tbTest tr:last');
if(container.find('td').length > 1)
{
$('#tbTest').append('<tr></tr>');
container = $('#tbTest tr:last');
}
$(container).append('<td><input type="text"/></td>');
I'm not sure if this code is 100% correct, but basically you need to check if the last tr
element contains more than one td
, and if it does, create a new one. 我不确定这段代码是否100%正确,但基本上你需要检查最后一个
tr
元素是否包含多个td
,如果是,则创建一个新的。
$(document).ready(function ($) {
var i = 0;
$("button").click(function () {
if (i % 2 != 0) {
row = $('<td><input type="text"/></td>');
row.appendTo('#tbTest tr:last-child');
} else {
row = $('<tr><td><input type="text"/></td></tr>');
row.appendTo('#tbTest');
}
i++
})
})
Here is a fiddle: http://jsfiddle.net/aK73x/5/ 这是一个小提琴: http : //jsfiddle.net/aK73x/5/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.