Строка строки удаления jquery
У меня есть таблица
<table id="favoriteFoodTable">
<th>
Food Name:
</th>
<th>
Restaurant Name:
</th>
<th>
</th>
<?php while ($row = $foods->fetch()) {
?>
<tr>
<td>
<?php echo $row['foodName']; ?>
</td>
<td>
<?php echo $row['restaurantName']; ?>
</td>
<td>
<a class="deleteLink" href="" >delete</a>
</td>
</tr>
<?php } ?>
</table>
Я использую эту функцию jquery, поэтому, когда пользователь нажимает на удаление, фон строки будет меняться, а затем строка удалит
$(document).ready(function() {
$("#favoriteFoodTable .deleteLink").on("click",function() {
var td = $(this).parent();
var tr = td.parent();
//change the background color to red before removing
tr.css("background-color","#FF3700");
tr.fadeOut(400, function(){
tr.remove();
});
});
});
только фон меняется, но строка не удаляется, почему? как решить?
Ответы
Ответ 1
Строка удаляется, но по щелчку заставляет вас следовать по ссылке, она немедленно восстанавливается, когда страница обновляется.
Добавить return false;
или event.preventDefault();
в конце обратного вызова, чтобы предотвратить поведение по умолчанию:
$(document).ready(function() {
$("#favoriteFoodTable .deleteLink").on("click",function() {
var tr = $(this).closest('tr');
tr.css("background-color","#FF3700");
tr.fadeOut(400, function(){
tr.remove();
});
return false;
});
});
Демонстрация
Обратите внимание, что я использовал closest
для более надежного кода: если между ними встанет другой элемент, tr
все равно будет найден.
Ответ 2
Что вы забыли сделать, так это установить хэш в вашей ссылке.
Пример:
<a class="deleteLink" href="" >delete</a>
должен быть
<a class="deleteLink" href="#" >delete</a>
или
return false;
в конце вашего
$(document).ready(function() {
$("#favoriteFoodTable .deleteLink").on("click",function() {
...
return false;
});
});
Ответ 3
Вот еще один вариант.
function DeleteRowOfProductTable(productID){
$('#YourTableId tr').each(function (i, row) {
var $row = $(row);
var productLabelId = $row.find('label[name*="Product_' + productID + '"]');
var $productLabelIdValue = $productLabelId.text();
if (parseInt(productID) == parseInt($productLabelIdValue))
{
$row.remove();
}
});
}
Ответ 4
Если вы хотите выбрать только одну строку в таблице за раз
$("#data tr").click(function() {
var selected = $(this).hasClass("highlight");
$("#data tr").removeClass("highlight");
if(!selected)
$(this).addClass("highlight");