覆盖 tr onclick

12

我在Django模板中有以下代码:

{% for item in items %}
  <tr onclick="{% url collection:viewitem item_id=item.id %}">
    <td>{{ item.name }}</td>
    <td>{{ item.date }}</td>
    <td>
      <button onclick="{% url collection:edititem item_id=item.id %}" type="button">Edit</button>
      <button onclick="{% url collection:removeitem item_id=item.id %}" type="button">Remove</button>
    </td>
  </tr>
{% endfor %}

然而,按钮的 onclick 事件不起作用,因为 tr 的 onclick 似乎覆盖了它。我该如何防止这种情况发生?

3个回答

21

请尝试以下操作:

<html>
    <body>
        <table >
            <tr onclick="alert('tr');">
                <td><input type="button" onclick="event.cancelBubble=true;alert('input');"/></td>
            </tr>
        <table>
    </body>
</html>

event.cancelBubble=true将禁止触发tr元素的点击事件


2
使用 event.stopPropagation() 就可以解决问题!

0
另一种方法: 为按钮创建单独的行,这样它就不会继承主行的tr onclick事件。类似这样:
<tr onclick="doSomething()">
   <td rowspan="2">A</td>
   <td rowspan="2">B</td>
   <td rowspan="2">C</td>
 </tr>
 <tr>
   <td><button type="button">Click</button></td>
 </tr>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接