0

我正在尝试通过 jQuery 动态添加表格行。一切正常,但该行不会将自身添加到最后一个 <tr>。相反,它将自身添加到 <table>...

我很困惑。谁能帮帮我?这是代码

Javascript

var counterx = 2;
var counter = 2;

$(document).ready(function(){
    $("#addMoreRcpt").click(function(){
        if (counterx>10){
            alert("Only 10 reciepients are allowed");
            return false;
        }

        var newTextBoxDiv = $(document.createElement('div')).attr("id", 'RcptEml_' + counter);
        newTextBoxDiv.append("<tr><td>New Data</td><td>New Data</td><td>New Data</td></tr>");

        newTextBoxDiv.appendTo("#RcptGroup");
        counter++;
        counterx++;
    });
});

function fncDelRcpt(id){
    $("#RcptEml_"+id).remove();
    counterx--;
}

HTML

<table border=1>
<div id="RcptGroup">
<tr>
    <th>1</th>
    <th>2</th>
    <th>3</th>
</tr>
<div id="1">
<tr>
    <td>data</td>
    <td>Data</td>
    <td>data</td>
</tr>
</div>
</div>

</table>
<br /><a id="addMoreRcpt" href="#" >Add more reciepients</a>
4

1 回答 1

1

这是您应该工作的代码的更改部分:

剧本:

$(document).ready(function() {
    $("#addMoreRcpt").click(function() {
        if (counterx > 10) {
            alert("Only 10 reciepients are allowed");
            return false;
        }
        var newTextBoxRow = $(document.createElement('tr')).attr("id", 'RcptEml_' + counter);
        newTextBoxRow.append("<td>New Data</td><td>New Data</td><td>New Data</td>");
        newTextBoxRow.appendTo("#RcptGroup");
        counter++;
        counterx++;
    });
});​

桌子:

<table border="1" id="RcptGroup">
    <tr id="0">
        <th>1</th>
        <th>2</th>
        <th>3</th>
    </tr>
    <tr id="RcptEml_1">
        <td>data</td>
        <td>Data</td>
        <td>data</td>
    </tr>
</table>​​​​​​​​​​​​

工作小提琴:http: //jsfiddle.net/pratik136/2au73/5/


正如对您问题的评论中所建议的那样,<Div/>s 不能嵌套在<Table/>s 中。这是 的指南HTML 4.01,但几乎所有内容都应该适用:http ://www.cs.tut.fi/~jkorpela/html/nesting.html

于 2012-08-12T23:18:25.807 回答