简体   繁体   English

如何解决表格行中的冲突点击事件?

[英]How to resolve conflicting click-events inside table-row?

I'm using jQuery to make HTML table rows expand on click. 我使用jQuery使HTML表行在单击时扩展。 Clicking any other row will collapse previously opened rows (as desired). 单击任何其他行将折叠以前打开的行(根据需要)。

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 : 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");
});

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

However, I also need an additional link (or button) that collapses the row. 但是,我还需要一个附加的链接(或按钮)来折叠该行。 Is there a way to resolve the conflicting click-events? 有没有办法解决冲突的点击事件? I tried a :not selector (as seen in the demo) and also working with z-index — without success. 我尝试了:not选择器(如演示中所示),并且还使用了z-index没有成功。

you need to use e.stopPropagation() 您需要使用e.stopPropagation()

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

This should work: 这应该工作:

$('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 http://www.bootply.com/KJV4AhxMRO

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

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