我有一个允许用户输入类次信息的表单(下面的屏幕截图)。
我创建了一个数组来保存表的值。当用户单击“添加”时,该值将添加到数组中
$(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();
})
最佳答案
这是一个与您的要求类似的示例。在您的情况下, .remove
上的单击事件监听器不起作用,因为在执行添加事件监听器时,元素在 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();
})
<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>
关于javascript - 删除单击按钮上的数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36460650/