如何制作<a> work inside clickable

时间:2019-05-24 19:03:57

标签: jquery html css

I have a table where each <tr> links to another page. This is code i use to archive this.

Table:

<tbody>
    <tr class="td-link" data-href="/invoice/preview/207/">
         <td>#14000059</td>
         <td>
             <a class="kt_ajax_link" data-invoiceid="207" data-csrf-token="43e848a61f3dadedc182a1454c8070550e4f275fe83d53ef1ac9f961281f1ba4" data-action="/invoice/delete/"><i class="fa fa-trash-alt"></i></a>
        </td>
    </tr>                                                                                                                                            
</tbody>

jQuery

$(".td-link").click(function() {
    window.location = $(this).data("href");
});

How can i make the link <a> work inside the table, without triggering the jQuery link?

I have tried with z-index, but cant get it working.

Any suggestions?

2 个答案:

答案 0 :(得分:1)

通过将此属性添加到<tr/>标签:<a>,可以防止click事件传播到onclick="event.stopPropagation();"

此处有更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

edit:并不是要窃取Mohamad的评论。如果他将其发布为答案将删除

答案 1 :(得分:1)

  • 首先,您必须替换此行:

    $(this).data(“ href”); 通过此行:

    $(this).attr(“ href”);

    • 第二,最好使用它:

      $(“ body”)。on('click','。td-link',function(e){..} 而不是$(“。td-link”)。click(..)

    • 最后,您可以按照@rosslh和@Mohammed的建议完成工作。

这是我测试过的一个示例,对我有用:

$("body").on('click','.td-link',function(e) {
    //e.preventDefault();
    //e.stopPropagation();
    var $link = $(this).attr("data-href");
    window.location = $link;
  });