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

时间:2015-12-13 00:22:34

标签: javascript jquery html

我使用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 - 但没有成功。

2 个答案:

答案 0 :(得分:0)

您需要使用e.stopPropagation()

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

答案 1 :(得分:0)

这应该有效:

$('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

相关问题