我是jQuery的初学者。我必须为每个表行添加和删除按钮。删除任何行时,我希望第一列值按升序序列化。现在我只是不明白。非常感谢您的帮助。
这些是我的jQuery代码:
$(function(){
$(".addButton").click(function(){
var x=document.getElementById('applyList');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var select = new_row.cells[1].getElementsByTagName('select')[0];
select.id += len;
select.value = '1';
var inp1 = new_row.cells[2].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = new_row.cells[3].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
x.appendChild( new_row );
});
$(document).on('click', '.deleteButton', function() {
var x = $('#applyList tr').length;
if(x == 2){
} else {
$(this).closest("tr").remove();
var row = $(this).closest("tr") // get to the row
row.children().each(function(){
});
}
});
});
这是html代码:
<table class="list" id="applyList">
<thead>
<tr>
<th class="thead color-white width-30">#</th>
<th class="thead color-white width-150">Route</th>
<th class="thead color-white width-50">Fare [MMK]</th>
<th class="thead color-white width-50">Remark</th>
<th class="thead color-white">
<button type="button" id="add" class="button-style tbl-button button-sm bg-color-sky-blue">ADD</button>
</th>
</tr>
</thead>
<tr>
<td>1</td>
<td>
<select>
<option value="1">Home->Office->Home</option>
</select>
</td>
<td><input type="text" class="width-50"/></td>
<td><input type="text" /></td>
<td>
<img class="addButton width-30 height-30 align-middle" src="../../public/img/busfare/plus.png"/>
<img class="deleteButton width-30 height-30 align-middle" src="../../public/img/busfare/minus.png"/>
</td>
</tr>
</table>
输出在这里:
答案 0 :(得分:0)
您可以使用splice()
方法从Array中删除元素。有关详细信息,请检查https://www.w3schools.com/jsref/jsref_splice.asp
答案 1 :(得分:0)
我假设当button#add
在表的末尾添加一行并且img.addButton
在该行之后添加一行时。在这里你有我的方法......
function createRow(id) {
var newrow = [
id,
'<select><option value="1">Home->Office->Home</option></select>',
'<input type="text" class="width-50"/>',
'<input type="text" />',
'<img class="addButton width-30 height-30 align-middle" src="../../public/img/busfare/plus.png"/><img class="deleteButton width-30 height-30 align-middle" src="../../public/img/busfare/minus.png"/>'
];
return '<tr><td>'+newrow.join('</td><td>')+'</td></tr>';
}
function renumberRows() {
$('table#applyList tbody tr').each(function(index) {
$(this).children('td:first').text(index+1);
});
}
$('button#add').click(function() {
var lastvalue = 1 + parseInt($('table#applyList tbody').children('tr:last').children('td:first').text());
$('table#applyList tbody').append(createRow(lastvalue));
});
$('table#applyList').on('click','.addButton',function() {
$(this).closest('tr').after(createRow(0));
renumberRows();
}).on('click','.deleteButton',function() {
$(this).closest('tr').remove();
renumberRows();
});
我希望它有所帮助