首页 > 解决方案 > 如何通过 jQuery 向表中添加行和列?

问题描述

我的页面上有下表:

<section class="content">

    <div class="box">
    
        <div class="box-header with-border">
    
            <div class="row margin-bottom-20">
                <div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12 text-end">
                
                    <a href="#" title="Novo Cadastro" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#InsertProduct"> <i class="fa fa-plus">  </i>New </a>
                
                </div>
            </div>  
    
        </div>
    
    </div>
    
<table class="table table-striped" id="QueryTable">
    
        <thead>
        
            <tr> 
            
                <th>Code: </th>
                <th class="text-center">Name: </th>
                <th class="text-center">Address: </th>
                <th class="text-center">Phone: </th>
                <th class="text-center">Options: </th>
            </tr>
        
        </thead>
        
        <tbody>

              <td>Code: </td>
              <td class="text-center">Name: </td>
              <td class="text-center">Address: </td>
              <td class="text-center">Phone: </td>
              <td class="text-center">Options: </td>

        </tbody>
    
    </table>

</section>

我需要通过 javascript 将行和列插入到这个表中。我试过类似的东西:

 $('#QueryTable').find('tr').each(function(){
        $(this).find('th').eq(n).after('<th>Test </th>');
   });

我也试过

$('#QueryTable tr').append('<th>Test</th>')

我也试过02:

$('#QueryTable tr').each(function()
{
    $(this).append('<th>Test</th>');
});

但是这些代码没有在我的表中插入行或列。如何通过javascript(纯或jquery)添加行和列?

标签: javascripthtmljqueryhtml-table

解决方案


这是一个简单的例子。我首先修复了您的表格,以便您的单元格位于一行内:

//adds the new column
$('#QueryTable thead tr').append('<th>Test</th>');

//adds a new cell to all existing rows (this assumes that the newly added column does not exist)
//at initialization
$('#QueryTable tbody tr').each(function() {
  $(this).append('<td>New Cell</td>');
});

//Adds a new row
$('#QueryTable tbody').append('<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-striped" id="QueryTable">
    
        <thead>
        
            <tr> 
                <th>Code: </th>
                <th class="text-center">Name: </th>
                <th class="text-center">Address: </th>
                <th class="text-center">Phone: </th>
                <th class="text-center">Options: </th>
            </tr>
        
        </thead>
        
        <tbody>
            <tr>
              <td>Code: </td>
              <td class="text-center">Name: </td>
              <td class="text-center">Address: </td>
              <td class="text-center">Phone: </td>
              <td class="text-center">Options: </td>
          </tr>
        </tbody>
    
    </table>


推荐阅读