取消列级链接时阻止行级链接

时间:2013-11-07 03:39:04

标签: javascript jquery

我有一张桌子......

<table class="data-table">
  <thead>
    <tr>
      <th width="16">ID</th>
      <th>Name</th>
      <th>Reference</th>
      <th>Link</th>
      <th>YouTube</th>
      <th>Status</th>
      <th width="16">Delete</th>
    </tr>
  </thead>
  <tbody>
    <tr class="clickable" data-href="/videos/1/">
      <td>1</td>
      <td>Test Video</td>
      <td></td>
      <td></td>
      <td></td>
      <td>
        <a href="/videos/delete/1" 
           onclick="return confirm_delete();">
          Delete
        </a>
      </td>
    </tr>
  </tbody>
</table>

脚本是......

<script>
  function confirm_delete() {
    var result = confirm("Are you sure you want to delete this video?");
    return result;
  }
</script>

单击该行将转到正确的URL。 单击“删除”链接会要求确认。如果我选择“确定”,则会转到正确的删除URL,但如果选择“取消”,则会取消删除URL,但会转到行级URL。我该如何防止这种情况?

2 个答案:

答案 0 :(得分:0)

<a href="/videos/delete/1"
  onclick="event.stopPropogation(); return confirm_delete();">Delete</a>

然而,帮自己一个忙,把你的javascript放在脚本标签中。

<a id="delete_1" href="/videos/delete/1">Delete</a>
...
<script>
    $('#delete_1').click(function(e) {
        e.stopPropogation();
        return confirm("Are you sure you want to delete this video?");
    });
</script>

答案 1 :(得分:0)

感谢所有评论/回答的人。我做了以下工作来解决问题。

首先,我删除了 onclick 属性,并在 a 标记中添加了一个类。

<td><a class="delete" href="/videos/delete/1">Delete</a></td>

然后我做了以下脚本。

<script>
  $(document).ready(function() {
    $('a.delete').click(function(event) {
      var result = confirm("Are you sure you want to delete this video?");

      if (!result) {
        event.preventDefault();
        event.stopPropagation();
      }
    });
  });
</script>