overriding tr onclick

overriding tr onclick

本文关键字:onclick tr overriding      更新时间:2023-09-26

我在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似乎覆盖了它。我如何防止这种情况发生?

请尝试以下操作:

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

事件.cancelBubble=true将抑制tr点击事件

使用event.stopPropagation()就可以了!

另一种方法:为按钮创建一个单独的行,这样它就不会继承主行的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>