gpt4 book ai didi

javascript - 移动附加了事件监听器的表行

转载 作者:行者123 更新时间:2023-12-03 07:15:00 25 4
gpt4 key购买 nike

我有一个用Bootstrap实现的表,即:

<table id="user-area-table" class="table">
<thead>
<tr>
<th>Name</th>
<th>Adjust</th>
<th>Visibility</th>
<th colspan="2">Order</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>

然后,用户通过选择填充表。表中的每一行都有许多可能的操作:向上、向下、删除等,我添加事件监听器以在使用 JQuery 预置/附加所需的表行后执行这些操作。

在诸如 up 之类的操作中,现有行将使用 JQuery 删除,我必须将其重新插入到 DOM 中。

$("#reference").on('click', '.fa-sort-asc', function(evt) {     $("#reference").prev().before($("#reference"));});

The issue I have is that I now have to add event listeners as the DOM elements are all new, yet I am within one of the event listener callbacks as is. I suspect the way to deal with this is to add some code which captures any event on a tr that I have added dynamically but I am uncertain how to do that.

Update:

To add a row into the table, this is what I am currently doing. Essentially I construct the table row html using a reference and name gleaned from the select and then I insert it into the table.

var rowdata = '<tr id="' + reference + '" class="prop-layer"><td>' + name + '</td><td><a href="#"><i class="fa fa-adjust"></i></a></td><td><input type="checkbox" name="checkbox1" class="slider" data-size="mini" checked></td><td><a href="#"><i class="fa fa-sort-asc"></i></a></td><td><a href="#"><i class="fa fa-sort-desc"></i></a></td><td><a href="#"><i class="fa fa-trash"></i></a></td></tr>';
$('#user-area-table tbody').prepend(rowdata);

最佳答案

您将事件处理程序分配给某个父级,例如 body,如下所示:

$("body").on('click', 'tr', function(evt) {
});

现在您可以动态移动 tr,它将保留其事件处理程序。您可以在这里阅读更多相关信息:http://api.jquery.com/on/ 这将指向 tr。

关于javascript - 移动附加了事件监听器的表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36467631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com