我有一个表单,允许用户输入班次信息(截图如下) 我创建了一个数组来保存表的值。当用户单击“添加”
时,该值将添加到数组中$(function () {
var TechnicianItems = [];
$('#TechnicianAdd').click(function () {
var isValidItem = true;
if (isValidItem) {
var $technicianId = parseInt($('#TechnicianId').val().trim());
var $technicianText = $('#TechnicianId').children("option").filter(":selected").text().trim();
var $shiftId = parseInt($('#ShiftId').val().trim());
var $shiftText = $('#ShiftId').children("option").filter(":selected").text().trim();
var $duration = parseFloat($('#TechnicianDuration').val().trim());
var $break = parseFloat($('#TechnicianBreak').val().trim());
var $comment = $('#TechnicianComment').val().trim();
TechnicianItems.push({
TechnicianId: $technicianId,
ShiftId: $shiftId,
Duration: $duration,
Break: $break,
Comment: $comment
});
// Clear the fields after insert.
$('#TechnicianId').val('');
$('#ShiftId').val('');
$('#TechnicianDuration').val('');
$('#TechnicianBreak').val('');
$('#TechnicianComment').val('');
// Append the newly added entry to #partlogs table.
$table = $('#shiftlogs>tbody').last();
$row = $('<tr/>');
$row.append($('<td/>').html($technicianText));
$row.append($('<td/>').html($shiftText));
$row.append($('<td/>').html($duration));
$row.append($('<td/>').html($break));
$row.append($('<td/>').html($comment));
$row.append($('<td/>').html('<input type="button" class="remove" value="Remove" />'));
$table.append($row);
} //END if(isValidItem)
}); // END $('#TechnicianAdd').click()
});
单击“删除”按钮时,如何从TehcnicianItems中删除项目?我尝试删除该行,但它也不起作用。
$('.remove').click(function() {
$(this).closest('tr').remove();
})
答案 0 :(得分:1)
这是一个类似于您的要求的示例。您的案例中.remove
上的click事件侦听器无法正常工作,因为在执行添加事件列表器时,元素在DOM中不可用。所以在文档上添加一个监听器
function add() {
var str = '<tr><td>' + $('#usrInp').val() + '</td><td> <button class="remove">Remove</button></td></tr>'
$('table').append(str);
$('#usrInp').val("");
}
$(document).on('click', '.remove', function() {
$(this).closest('tr').remove();
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type=text id="usrInp">
</td>
<td>
<button onclick="add()">Add</button>
</td>
</tr>
<tr>
<td>Row 1</td>
<td>
<button class="remove">Remove</button>
</td>
</tr>
<tr>
<td>Row 2</td>
<td>
<button class="remove">Remove</button>
</td>
</tr>
<tr>
<td>Row 3</td>
<td>
<button class="remove">Remove</button>
</td>
</tr>
<tr>
<td>Row 4</td>
<td>
<button class="remove">Remove</button>
</td>
</tr>
</table>
&#13;