所以我试图使用Jquery获取我的表的行索引,但是我的代码为每一行返回相同的索引号。我需要找到删除所选行的索引。但是,此代码仅删除最后一个值 到目前为止我尝试了什么:
function updateCredentialList() {
var index = $('.existingCredential').find('tr').closest('tr').index();
var i = $('.existingCredential').find('tr:eq('+index+')').remove();
alert(index);
}
我的表:
<c:choose>
<c:when test="${action == 'edit'}">
<td class="data">
<input type="hidden" name="pkAdminCredentials" value="${environment.pkAdminCredentialIds}">
<input type="hidden" name="dbCredentials" value="${environment.dbCredentialIds}">
<table class="existingCredential">
<tr>
<th>Primary?</th>
<th>Username</th>
<th>Password</th>
<th>ID</th>
</tr>
<c:forEach var="each" items="${environment.pkAdminCredentials}">
<tr>
<td class="edit">${each.primary ? 'Yes' : 'No'</td>
<td class="edit">${each.username}</td>
<td class="edit">${each.password}</td>
<td class="edit">${each.id}</td>
<td><a class="editCredential" class="openWindow" data-modal-id="existingCredential" data-credential-id="${each.id}">Edit</a></td>
<td><a href="#">Delete</a></td>
</tr>
</c:forEach>
</table>
</td>
</c:when>
</c:choose>
答案 0 :(得分:0)
要使用jQuery获取当前索引,一种可能性是函数index。
让我们创建一个包含3行的简单表格,并为每一行创建一个onclick事件处理程序:
$(function () {
$('table').find('tr').on('click', function(e) {
$(this).data('isSelected', true);
$(this).siblings().data('isSelected', false);
$('#log').append('<p>Current Index Row is: ' + $('table').find('tr').index(this) + '</p>')
});
$('#btn').on('click', function(e) {
var selectedRow = $('table').find('tr').filter(function(index, element) {
return $(this).data('isSelected') == true;
});
if (selectedRow.length == 1) {
selectedRow.remove();
}
});
});
&#13;
table, th, td {
border: 1px solid black;
width: 30%;
}
&#13;
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<table>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>u1</td>
<td>Jackson</td>
<td>100</td>
</tr>
</table>
<p>Click on a table row</p>
<button id="btn">Remove the selected ROW (click on it before)</button>
<div id="log"></div>
&#13;