如何解决表行内冲突的单击事件

How to resolve conflicting click-events inside table-row?

本文关键字:冲突 单击 事件 何解决 解决      更新时间:2023-09-26

我使用jQuery使HTML表行在单击时展开。单击任何其他行将折叠以前打开的行(根据需要)。

HTML

<table class="table table-hover">
    <tbody>
        <tr>
            <td>
                Click to expand
                <div class="details hidden" ><a href="#" class="collapse-row">Close</a></div>
            </td>
        </tr>
    </tbody>
</table>

JavaScript

$('tr:not(a.collapse-row)').click(function(){
  console.log("Expand row");
  $('.details').addClass("hidden");
  $(this).find('.details').removeClass("hidden");
});    
$('.collapse-row').click(function(e){
  e.preventDefault();
  console.log("Collapse row");
  $('.details').addClass("hidden");
});

演示:http://www.bootply.com/KGu1lDO9PS

但是,我还需要一个额外的链接(或按钮)来折叠行。有没有办法解决冲突的点击事件?我尝试了:not选择器(如演示中所示),同时也使用了z-index,但没有成功。

您需要使用e.stopPropagation()

$('.collapse-row').click(function(e){
  e.preventDefault();
  e.stopPropagation();
  console.log("Collapse row");
  $('.details').addClass("hidden");
});

这应该有效:

$('tr').click(function() {
    // Expand clicked row
    $(this).find('.details').removeClass("hidden");
    // Hide all other rows
    $(this).siblings().find('.details').addClass("hidden");
})
$('.collapse-row').click(function(e){
    e.preventDefault();
    // Close to open row
    $(this).addClass("hidden");
})

http://www.bootply.com/KJV4AhxMRO