jquery - 使用 jQuery 在 DOM 中添加事件后单击不起作用
问题描述
我知道这看起来像是一个基本问题。我一直在玩,delegation
但仍然得到相同的结果。
我试图使它工作的列表上的删除按钮,它只工作第一个但如果我添加一个新的它不会工作
//variables
let $questions = $('.quiz-questions');
let $tableOptionQuestions = $('.survey-list-service');
let $addNewOption = $('.add-option');
let $removeOption = $('.remove-option');
//events
$addNewOption.on("click", addNewOptionFunc );
$removeOption.on("click", removeOptionFunc );
//add new option
function addNewOptionFunc (e) {
let $optionRow = $(this).prev().children('tbody').children('tr').first();
$optionRow.clone().appendTo( "tbody" );
}
//remove option
function removeOptionFunc (e) {
let $optionRow = $(this);
let $sizeRow = $tableOptionQuestions.find('tbody tr').length;
// if( $tableOptionQuestions.find('tbody tr').length != 1 ) {
$optionRow.closest('tr').remove();
// }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quiz-questions">
<section>
<table class="survey-list-service">
<thead>
<tr>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value=""></td>
<td><button class="button button-primary remove-option">remove</button></td>
</tr>
</tbody>
</table>
<button class="button button-primary add-option">Add </button>
</section>
</div>
解决方案
为动态添加的元素绑定这样的事件。
$(document).on("click", '.add-option', addNewOptionFunc);
$(document).on("click", '.remove-option', removeOptionFunc);
//variables
let $questions = $('.quiz-questions');
let $tableOptionQuestions = $('.survey-list-service');
//events
$(document).on("click", '.add-option', addNewOptionFunc);
$(document).on("click", '.remove-option', removeOptionFunc);
//add new option
function addNewOptionFunc(e) {
let $optionRow = $(this).prev().children('tbody').children('tr').first();
$optionRow.clone().appendTo("tbody");
}
//remove option
function removeOptionFunc(e) {
let $optionRow = $(this);
let $sizeRow = $tableOptionQuestions.find('tbody tr').length;
// if( $tableOptionQuestions.find('tbody tr').length != 1 ) {
$optionRow.closest('tr').remove();
// }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quiz-questions">
<section>
<table class="survey-list-service">
<thead>
<tr>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value=""></td>
<td><button class="button button-primary remove-option">remove</button></td>
</tr>
</tbody>
</table>
<button class="button button-primary add-option">Add </button>
</section>
</div>
推荐阅读
- javascript - 道具在单次刷新中更新 3 次
- google-cloud-platform - 从谷歌云平台 linux 框中的 google-sudoers 中删除用户
- powershell-4.0 - 无法创建 com 对象 - Powershell
- azure-devops - 在 Azure DevOps 中,由于权限问题,开发人员无法访问冲刺板和其他板
- javascript - 在 Odoo 10 的小部件中显示 FormView
- list - 从列表中设置背景
- android - 从 Activity 上下文错误之外调用 startActivity()
- r - 条件下的 R 循环
- gyroscope - 如何获取传感器时间戳和移动时间戳以便在 Xcode 中同步两个 Movesense 传感器?
- javascript - 如何使用JS在html中添加和删除客户?