简体   繁体   English

新增中 <tr><td> 在具有Javascript的div中未在表格中显示

[英]Adding <tr> <td> within a div with Javascript not showing within the table

I have a HTML table as below : 我有一个HTML表,如下所示:

    <table>
        <tr>
            <th>Name</th>
            <th>Class</th>
            <th>Reg ID</th>
        </tr>
        <tr>
            <td>Alex</td>
            <td>VII</td>
            <td>56733</td>
        </tr>

        <div id="addfield"></div>

    </table>    

<input type="button" value="add" id="add_more_fields" />

And the jquery : 和jQuery:

$(document).ready(function(){
    var html = '';
    $('#add_more_fields').click(function(){
        html += '<tr>';
        html += '<td>Steve</td>';
        html += '<td>X</td>';
        html += '<td>87777</td>';
        html += '</tr>';

        $('#addfield').append(html);

    });
});

I wanted to add the <tr> generated by the javascript to be within the table. 我想将由javascript生成的<tr>添加到表中。 but when I clicked the button, the output is shown outside the table ! 但是当我单击按钮时,输出显示在表的外面! How can I display it within the table ? 如何在表格中显示它?

DEMO Here 在这里演示

Try tbody inplace of #addfield like, 尝试用tbody #addfield

<table>
   <thead>
    <tr>
        <th>Name</th>
        <th>Class</th>
        <th>Reg ID</th>
    </tr>
  </thead>
  <tbody>
    <tr>
        <td>Alex</td>
        <td>VII</td>
        <td>56733</td>
    </tr>
   </tbody>
</table> 

SCRIPT 脚本

$('#add_more_fields').click(function(){
    html += '<tr>';
    html += '<td>Steve</td>';
    html += '<td>X</td>';
    html += '<td>87777</td>';
    html += '</tr>';
    $('tbody').append(html);
});

Demo 演示版

It is not working because div inside table is invalid HTML structure. 它不起作用,因为table内的div是无效的HTML结构。 Append row to the table itself. 将行追加到表本身。

Also, you are not clearing the string html. 另外,您不会清除字符串html。 Which causes multiple rows. 这导致多行。

$('#add_more_fields').click(function () {
    var html = ''; //declare string inside function
    html += '<tr>';
    html += '<td>Steve</td>';
    html += '<td>X</td>';
    html += '<td>87777</td>';
    html += '</tr>';
    $('table').append(html);
});

Updated fiddle here. 在这里更新了小提琴。

Append Inside table 追加表内

$('#add_more_fields').on('click',function(){
    html += '<tr>';
    html += '<td>Steve</td>';
    html += '<td>X</td>';
    html += '<td>87777</td>';
    html += '</tr>';
    $('table').append(html);//If you have more table then use id for table to append
});

You can't have a div inside a table. 表格内不能有div。 All you've gotta do is put the id on the table and remove the div. 您要做的就是将ID放在桌子上,然后删除div。

<table id='addfield'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM