簡體   English   中英

動態添加td和tr onLlick HTML JQUERY

[英]Dynamically add td and tr onclick HTML JQUERY

我有一個有一行和兩個TD的表

<table id="tbTest">
    <tr>
        <td>
            <input type="text">
        </td>
        <td>
            <input type="text">
        </td>
    </tr>
</table>

我還有一個按鈕,動態地添加一個帶有td的新行。 如果第二次點擊我想添加第二個td。 如果第三次點擊我想添加一個新的tr與一個td ...等

單擊jquery

var counter = 2;

if ((counter % 2) == 0) {
    row = $('<tr><td><input type="text"/></td></tr>');
}
else {
    //???????????????
}
row.appendTo('#tbTest');
counter++;

我可以添加一個tr和td(第一次點擊)但第二次點擊我如何在tr ...建議中插入第二個td?

謝謝,

從你的問題來看,我想你要實現的是在第一次點擊按鈕時添加一個包含表數據的新行,每隔一個奇數時間(第三次,第五次等)添加新行,並將新表數據添加到創建的行當按鈕被點擊第二次,每隔一次甚至是時間(第四次,第六次等)

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
}
});

這是一個工作小提琴: http//jsfiddle.net/976PT/

像這樣的東西會起作用:

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>');

我不確定這段代碼是否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++
    })
})

這是一個小提琴: http//jsfiddle.net/aK73x/5/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM