Javascript:捕获并防止 HTML 表格中的重复行条目

问题描述 投票:0回答:3

我的页面上目前有两个表,我现在可以将表 1 中的记录添加到表 2 中,但我想添加条件来检查该新记录是否已存在于我的 table2 中。这是我的桌子:

 <div id="opTableDiv" class="tableFixHead" ; style="margin-top: 5px;">
        <table class="sortable" border="1" id="table1">
            <thead>
                <tr>
                    <th>ID Number</th>
                    <th>Name</th>
                </tr>
            </thead>
            <tbody>               
                <tr style="font-size:11px">
                </tr>                
            </tbody>
        </table>
    </div>



 <div id="NewTraining" style="display:none">        
        <div id="opTableDiv" class="tableFixHead">            
            <table class="sortable" border="1" id="table2">
                <thead>
                    <tr>
                        <th>ID Number</th>
                        <th>Name</th>
                        <th>Action</th>

                    </tr>
                </thead>
                <tbody>
                    <tr id="TrainTR" style="font-size:11px">
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

这是我的 javascript,用于添加新记录并需要在此处进行验证以避免重复使用 id 作为其唯一值:

function AddRecord(that, id, name) {

        var table = document.getElementById("table2");

        var row = table.insertRow(1);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);

        cell1.innerHTML = id;
        cell2.innerHTML = name;

任何建议/意见TIA。

javascript html
3个回答
1
投票

这可以通过以下方式实现:

  1. 首先迭代
    tr
    table2
    行元素,其中,对于每次迭代
  2. 您检查当前行上
    innerHTML
    单元格元素的
    td
    值,看看它们是否与您的输入参数匹配,并且,
  3. 如果检测到匹配,则通过
    AddRecord()
    语句提前退出
    return
    函数

实现这一点的方法有很多种。一种选择是使用

querySelector()
方法提取
tr
元素进行迭代,具体进行比较的
td
元素如下:

function AddRecord(that, id, name) {

  var table = document.getElementById("table2");

  /*
  Extract and iterate rows from tbody of table2
  */
  for(const tr of table.querySelectorAll("tbody tr")) {
     
    /*
    Extract first and second cell from this row
    */
    const td0 = tr.querySelector("td:nth-child(1)");
    const td1 = tr.querySelector("td:nth-child(2)");
    
    /*
    If this row has missing cells, skip it
    */
    if(!td0 || !td1) {
      continue;
    }
    
    /*
    Check if cells of existing tr row contain same contents
    as input arguments. Note also the use of == rather than 
    the use of === to allow type coercion when comparing 
    number id with string id.
    */
    if ((td0.innerHTML == id) && (td1.innerHTML == name)) {
      
      console.log(`Match found for ${id} and ${name}. Insert rejected`);
      return;
    }
  }  

  var row = table.insertRow(1);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);

  cell1.innerHTML = id;
  cell2.innerHTML = name;
}

AddRecord('', 1, 'bob')
AddRecord('', 2, 'jon')
AddRecord('', 1, 'bob') // Should fail to insert
AddRecord('', 3, 'jon')
AddRecord('', 2, 'jon') // Should fail to insert
<div id="NewTraining" >
  <div id="opTableDiv" class="tableFixHead">
    <table class="sortable" border="1" id="table2">
      <thead>
        <tr>
          <th>ID Number</th>
          <th>Name</th>
          <th>Action</th>

        </tr>
      </thead>
      <tbody>
        <tr id="TrainTR" style="font-size:11px"> 
        </tr>
      </tbody>
    </table>
  </div>
</div>

希望这有帮助!


0
投票

我有一个附加到单击事件的函数,用于将一行添加到表中,其实现的一部分是这样的:

    var cartTotal = $('#cart_total').val();
    var cartDiscount = $('#cart_discount').val();
    var cartType = $('input[name="cart_type"]:checked').val();
    var cartTypeLabel = (
        cartType == 0 ? 'percentage' : 'fixed amount'
    );
    var duplicatedRow = false;

    $('#discount_rules_table tr').each(function (index, tr) {
        //if it is not the header row
        if(index!==0) {
            var tds = $(tr).find("td");
            if(duplicatedRow){
                return;
            } else {
                duplicatedRow = (
                    tds[0].innerHTML == cartTotal 
                    && tds[1].innerHTML == cartDiscount 
                    && tds[2].innerHTML.toLowerCase() == cartTypeLabel.toLowerCase()
                );
            }
        }
    });

    if(duplicatedRow) {
        return;
    }
    //...

使用上面的代码,我可以避免重复的行。


0
投票

我使用此函数在附加新行之前检查该表的每一行。希望这有帮助。

function checkDuplicateEntry(Col1, Col2, tablename){
    $('#'+tablename+' tbody tr').each(function () {
        td1 = $(this).find('td:eq(0)').text() //td1 is like first column of that row
        td2 = $(this).find('td:eq(1)').text()
        if(td1 !== Col1 && td2 !== Col2){
            $('#'+tablename+' > tbody').append('<tr><td>'+ Col1 + '</td><td>' + Col2 + '</td></tr>');
        }
        
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.