我想阻止用户删除表中的所有行。我已经放入了一个if语句来防止在加载时删除第一行,如何获取if语句中使用的所有表行的计数,这样我就可以删除所有行,只要删除后至少有一行?
我的语法是:
<table class="authors-list">
<tr><td>author's first name</td><td>author's last name</td></tr>
<tr><td><input type="text" name="first_name" /></td><td><input type="text" name="last_name" /></td><td><a class="deleteRow"> x </a></td></tr>
<script type="text/javascript">
var counter = 1;
jQuery("table.authors-list").on('change','input[name^="first_name"]',function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr><td><input type="text" name="first_name' +
counter + '" /></td><td><input type="text" name="last_name' +
counter + '" /></td><td><a class="deleteRow"> x </a></td></tr>');
jQuery('table.authors-list').append(newRow);
});
jQuery("table.authors-list").on('click','.deleteRow',function(event){
console.log('h');
if (counter==1) { alert ('form must have at least one row')} else {
$(this).closest('tr').remove();
}
});
</script>
一如既往地谢谢,
答案 0 :(得分:2)
您可以使用
if ($(this).closest('table').find('tr').length<2) {
alert ('form must have at least one row')
} else {
$(this).closest('tr').remove();
}
答案 1 :(得分:1)
我们再见面.....反正
试试这个
jQuery("table.authors-list").on('click','.deleteRow',function(event){
if ($(this).parents('table').find('tr').length > 2) {
$(this).closest('tr').remove();
}else{
alert ('form must have at least one row')
}
});
答案 2 :(得分:1)
假设你没有为了简洁起见而没有包括所有标记,我很想尝试这些方面:
<table class="authors-list">
<!-- for one thing, let's separate our table structure a little better -->
<thead>
<tr>
<td>author's first name</td>
<td>author's last name</td>
</tr>
</thead>
<!-- ... in this way, you don't have to manually exclude the header rows from your count -->
<tbody>
<tr>
<td>
<input type="text" name="first_name" />
</td>
<td>
<input type="text" name="last_name" />
</td>
<td><a class="deleteRow"> x </a>
</td>
</tr>
</tbody>
</table>
然后您可以转到javascript: (完全没必要在选择器中包含表格标签......你的类名应该可以正常用于这些目的,并为你节省一些字符,顺便说一下......)
jQuery(".authors-list tbody").on('change', 'input[name^="first_name"]', function (event) {
event.preventDefault();
// get the number of rows, here
var counter = $(".authors-list tbody tr").length;
// also, you don't need to wrap newRow in a jQuery() call... append() does that for you
var newRow = '<tr><td><input type="text" name="first_name' + counter + '" /></td><td><input type="text" name="last_name' + counter + '" /></td><td><a class="deleteRow"> x </a></td></tr>';
jQuery('.authors-list tbody').append(newRow);
});
jQuery(".authors-list tbody").on('click', '.deleteRow', function (event) {
// get the counter at the point in time when you're trying to test deletion
var counter = $(".authors-list tbody tr").length;
if (counter == 1) {
alert('form must have at least one row')
} else {
$(this).closest('tr').remove();
}
});