我有一个看起来像这样的表:
<table>
<thead>
<!-- random table headings -->
</thead>
<tbody>
<tr class="readonly">
<td><input type="text" readonly="readonly" name="bookings[start][]" class="date" value="start"/></td>
<td><input type="text" readonly="readonly" name="bookings[end][]" class="date" value="end"/></td>
<td><input type="text" readonly="readonly" name="bookings[comment][]" value="comment"/></td>
<td>
<button type="button" class="control edit" title="Edit this row">Edit</button>
<button type="button" class="control delete" title="Delete this row">×</button>
<!-- delete button needs to know the posistion of the row
in the table so that it can remove its array entry -->
</td>
</tr>
<!-- ^ inserted as required by the button in tfoot -->
</tbody>
<tfoot>
<tr>
<td><input type="text" id="startinput" class="date" value=""/></td>
<td><input type="text" id="endinput" class="date" value=""/></td>
<td><input type="text" id="commentinput" value=""/></td>
<td><button type="button" class="control add" title="Add to the table">+</button></td>
</tr>
</tfoot>
</table>
为了正确实现删除按钮,需要计算可以找到按钮的行的索引。我怎么能在jQuery中做到这一点?这是当前的代码:
$("button.delete").live("click",function()
{
var row = $(this).parent().parent();
row.addClass("deleting");
if(confirm("delete this row?"))
{
var row idx = /*???*/;
datelist.bookings.splice(idx,1);
row.remove();
}
else
{
row.removeClass("deleting");
}
});
感谢。
答案 0 :(得分:5)
这将为您提供tbody中行的从零开始的索引。
var row_idx = row.prevAll().length;
仅供参考,技术上tfoot应出现在tbody之前(正确的HTML)。此外,技术上可能有多个tbody元素。