【问题标题】:overriding tr onclick覆盖 tr onclick
【发布时间】:2011-09-04 11:05:45
【问题描述】:

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

【问题讨论】:

    标签: javascript html django-templates


    【解决方案1】:

    请尝试以下方法:

    <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() 就可以了!

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2011-08-26
          • 1970-01-01
          • 2013-03-23
          • 1970-01-01
          • 2013-07-07
          • 2013-07-16
          • 2013-09-29
          • 1970-01-01
          • 2017-04-19
          相关资源
          最近更新 更多