代码之家  ›  专栏  ›  技术社区  ›  Sean Kimball

当jQuery用于检测行上的单击时,无法单击表行中的复选框

  •  0
  • Sean Kimball  · 技术社区  · 8 年前

    这里发生了一件奇怪的事情,我有一个包含行的数据表,可以通过单击行中的任何单元格来选择行,最后一个单元格附带了一些其他函数,因此它可以选择行(选中复选框),但不能取消选中它:

    以下是标记:

    <tr class="82510246 inventory-row">
    
    <td>
         <input type="checkbox" value="82510246" name="tags[]" id="tag82510246" class="checkbox inventory-checkbox">
    </td>
    
    <td>40003</td>
    ... a whole bunch of cells ...
    <td>430</td>
    
    <td class="inventory-price">
         <a class="tag-price">0.7289</a>
    </td>
    
    </tr>
    

    以及JQUERY:

    $('.inventory-row').on('click', 'td', function(event) {
        var css = $(this).attr('class');
        var box = $(this).closest('tr').find(':checkbox').is(':checked');
        if(css !== 'inventory-price'){
            $(this).closest('tr').find(':checkbox').trigger('click');
        }  
        if(css == 'inventory-price' && !box){
            $(this).closest('tr').find(':checkbox').trigger('click');
        }   
    });
    

    我不能直接单击单元格/复选框-如果我单击该单元格,则不会发生任何事情(复选框不会选择/取消选择)
    为什么没有发生?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Tasos Fel    8 年前

    您尝试在每个td上添加事件单击,因此代码中存在冲突,因为您的复选框位于 td 也添加一个类,如“ td-text “在您的td上,您希望可以单击,但使用checbox时除外。

    $('.inventory-row').on('click', '.td-text', function(event) {
        var css = $(this).attr('class');
        var box = $(this).closest('tr').find(':checkbox').is(':checked');
        if(css !== 'inventory-price'){
            $(this).closest('tr').find(':checkbox').trigger('click');
        }  
        if(css == 'inventory-price' && !box){
            $(this).closest('tr').find(':checkbox').trigger('click');
        }   
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <table>
      <tr class="82510246 inventory-row">
    
    <td>
         <input type="checkbox" value="82510246" name="tags[]" id="tag82510246" class="checkbox inventory-checkbox">
    </td>
    
    <td class="td-text">40003</td>
    ... a whole bunch of cells ...
    <td class="td-text">430</td>
    
    <td class="inventory-price">
         <a class="tag-price">0.7289</a>
    </td>
    
    </tr>
    </table>