【问题标题】:Add new row before specific element在特定元素之前添加新行
【发布时间】:2020-08-17 19:04:27
【问题描述】:

我的表格由 DAYS - 星期一、星期二 .... 和每一天的行组成。

表格中的每一天都有添加按钮

通过点击添加按钮,JS 将新行添加到特定日期(星期一、星期二等...)。

目前,JS 直接在 <tr> 元素内添加新行,其中存储了 ADD 按钮。

我希望通过单击添加按钮,在下一个 <tr class="day"> 元素之前添加新行

我已经尝试过:.append()、.appendTo()、.before()、.insertBefore(),其中任何一个都不适合我。

任何想法如何做到这一点? --> 将新行添加到表格部分的末尾(或表格的下一部分之前)。

$this元素:

`<a class="add_fields btn btn-primary workingday-row" data-id="70358063118960" data-fields="<tr>  <td><input label=&quot;false&quot; type=&quot;time&quot; name=&quot;teacher[working_days_attributes][0][working_hours_attributes][70358063118960][from]&quot; id=&quot;teacher_working_days_attributes_0_working_hours_attributes_70358063118960_from&quot; /></td>  <td><input label=&quot;false&quot; type=&quot;time&quot; name=&quot;teacher[working_days_attributes][0][working_hours_attributes][70358063118960][to]&quot; id=&quot;teacher_working_days_attributes_0_working_hours_attributes_70358063118960_to&quot; /></td>  <td>    <input type=&quot;hidden&quot; value=&quot;false&quot; name=&quot;teacher[working_days_attributes][0][working_hours_attributes][70358063118960][_destroy]&quot; id=&quot;teacher_wor`king_days_attributes_0_working_hours_attributes_70358063118960__destroy&quot; />    <a class=&quot;remove_record&quot; href=&quot;#&quot;>Remove wokring Hour</a>  </td></tr" href="#">Add Working Hour</a> 

jquery部分代码:

$(this).closest('tr').append($(this).data('fields').replace('booking_booking_working_days_working_day_id', time));

HTML:

    <tr class="day">
      <td>
        Monday
      </td>
    </tr>
    <tr>
      <td>HERE IS MY ADD BUTTON</td>
      <tr>
         HERE ARE NEWLY ADDED FIELDS
      </tr>
    </tr>
      HERE I WOULD LIKE TO HAVE NEWLY ADDED FIELDS (probably inside another <tr></tr>)
    <tr class="day">
      <td>
        Tuesday
      </td>
    </tr>

【问题讨论】:

  • 你试过.after().insertAfter()吗?

标签: javascript jquery


【解决方案1】:

.append(html) 将 html 插入到它被调用的元素中。相反,您可以使用.insertAdjacentElement('afterend', html)。这里的关键是 'after end 告诉要插入 html after the targetElement itself.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 2011-12-12
    • 2018-09-17
    • 1970-01-01
    相关资源
    最近更新 更多