jQuery动态生成的html表

时间:2019-02-09 22:56:07

标签: jquery html django

我有多个动态生成的HTML表。表格的每一行都有一个“编辑”按钮。 使用以下代码,仅针对第一个表上的按钮触发click事件。它不适用于后续表格。请帮助我使它适用于所有桌子。

在我的Django模板中:

{% for parent in parents %}
  <table class="table" id="my-table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      {% for child in parent.children %}
        <tr>
          <td>{{ child.name }}</td>
          <td>{{ child.age }}</td>
          <td>
            <button type="button" class="btn-edit" data-url="{% url "app:child-update" child.id %}">
              <span class="glyphicon glyphicon-pencil"></span> Edit
            </button>
          </td>
    </tbody>
  </table>
{% endfor %}

JavaScript代码:

$(function () {

  var loadForm = function () {
  // ....
 }
};

$("table").on("click", ".btn-edit", loadForm);

1 个答案:

答案 0 :(得分:0)

Django模板:

{% for parent in parents %}
  <table class="table" id="my-table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      {% for child in parent.child_set.all %}
        <tr>
          <td>{{ child.name }}</td>
          <td>{{ child.age }}</td>
          <td>
            <button type="button" class="btn-edit" data-url="{% url 'app:child-update' child.id %}">
              <span class="glyphicon glyphicon-pencil"></span> Edit
            </button>
          </td>
         </tr>
         {% empty %}
         <tr>
           <td>No Records yet.</td>
         </tr>
         {% endfor %}
    </tbody>
  </table>
{% endfor %}

jQuery:

$(function () {  
    var loadForm = function () {
      // ...
    };

    $("table").on("click", ".btn-edit", loadForm);

  });