1 回答

TA貢獻1780條經驗 獲得超1個贊
有很多方法可以做到這一點。
一種方法是在所有行中都有兩個按鈕,并使用 CSS 隱藏其中一個或另一個。
例如:
.table_1 .borrar { display:none; }
.table_2 .agregar { display:none; }
根據信息的不同,您可能不希望人們打開檢查器、顯示按鈕并單擊它。沒什么大不了的,但就像我說的,這取決于你用它做什么。
如果您想對其進行編碼,則必須在附加按鈕之前修改按鈕。
像這樣的東西
var row = $(this).closest('tr');
var button = row.find('.btn');
button.removeClass('agregar').addClass('borrar');
button.find('.glyphicon').removeClass('glyphicon-plus').addClass('glyphicon-trash');
但是等等,您原來的“點擊”事件仍在被觸發。為什么?因為即使您交換了類,您也已為每個類附加了一個方法。
為了讓您的新按鈕正常工作,您需要附加這樣的方法
$("body").on("click", ".agregar", function(event){ ... }
$("body").on("click", ".borrar", function(event){ ... }
這將告訴代碼在每個 .agregar 和 .borrar 元素事件上運行(如果它們是新添加的)。
這是一個例子
$(document).ready(function() {
$("body").on("click", ".agregar", function(event) {
event.preventDefault();
var row = $(this).parents('tr');
var button = row.find('.btn');
button.removeClass('agregar').addClass('borrar');
button.find('.glyphicon').removeClass('glyphicon-plus').addClass('glyphicon-trash');
$('#tablaSala').append(row);
});
$("body").on("click", ".borrar", function(event) {
event.preventDefault();
var row = $(this).parents('tr');
var button = row.find('.btn');
button.removeClass('borrar').addClass('agregar');
button.find('.glyphicon').removeClass('glyphicon-trash').addClass('glyphicon-plus');
$('#tablaDisponibles').append(row);
});
});
table {
margin-bottom: 40px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tablaDisponibles" border="1">
<tr>
<td>Row 1</td>
<td><button class="btn agregar"><span class="glyphicon glyphicon-plus"></span></button></td>
</tr>
</table>
<table id="tablaSala" border="1">
<tr>
<td>Row 2</td>
<td><button class="btn borrar"><span class="glyphicon glyphicon-trash"></span></button></td>
</tr>
</table>
- 1 回答
- 0 關注
- 124 瀏覽
添加回答
舉報