我有一行,我想将数据发送到另一个页面,同时单击“添加”按钮。然后我想删除“添加”类并添加“删除”类,如果我点击“删除”,则再次删除它并添加“添加”类。我的代码在下面,但它不能正常工作
$(function() {
//selecting a class that contains "btn" and "add" class
$('.btn.add').click(function() {
$(this).text("remove");
$(this).addClass("remove");
$(this).removeClass("add");
var $row = $(this).closest("tr"),
$name = $row.find("td:nth-child(2)"),
$id = $row.find("td:nth-child(1)");
$.ajax({
type: 'POST',
dataType: 'json',
url: 'feed.php',
data: {
meal: $name.text(),
day: $id.text()
},
success: function(msg) {
$row.css({
'background-color': 'rgba(76, 175, 80, 0.3)'
});
}
});
});
//selecting a class that contains "btn" and "add" class
$('.btn.remove').click(function() {
$(this).removeClass("remove");
$(this).addClass("remove");
$(this).text("add");
var $row = $(this).closest("tr"),
$name = $row.find("td:nth-child(2)"),
$id = $row.find("td:nth-child(1)");
$.ajax({
type: 'POST',
dataType: 'json',
url: 'feed.php',
data: {
meal: $name.text(),
day: $id.text()
},
success: function(msg) {
$('#note').html(msg.aaa + ' ' + msg.bbb + ' ' + msg.ccc);
$row.css({
'background-color': 'rgba(255, 0, 0, 0.3'
});
}
});
});
});
实际上,我无法理解您的主要问题,但是您的代码可以缩小如下,无需仅出于类的原因再次重复您的代码。
$('.btn').click(function(){
// to change the text
if($(this).text().trim() === 'add') {
$(this).text('remove')
} else {
$(this).text('add')
}
// to change the class name
if($(this).hasClass('add')) {
$(this).addClass('remove').removeClass('add')
} else {
$(this).addClass('add').removeClass('remove')
}
// further code here conditionally
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句