我有以下js代码:
$("#add_station").on('click', function () {
$(this).closest('form').submit(function () {
alert("working!");
$.ajax({
url: advoke.base_url + "/new-vendor-user/station/ajax",
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: new FormData(this),
beforeSend: function () {
$('.info').hide().find('ul').empty();
$('.success_message').hide().find('ul').empty();
$('.db_error').hide().find('ul').empty();
},
success: function (data) {
if (!data.success) {
$.each(data.error, function (index, val) {
$('.info').find('ul').append('<li>' + val + '</li>');
});
$('.info').slideDown();
setTimeout(function () {
$(".info").hide();
}, 5000);
} else {
$('.success_message').slideDown();
$('#add_station').remove();
$("#station").append(data.new_station);
setTimeout(function () {
$(".success_message").hide();
}, 5000);
} //success
},
error: function () {
//db error
$('.db_error').append('<li>Something went wrong, please try again!</li>');
$('.db_error').slideDown();
//Hide error message after 5 seconds
setTimeout(function () {
$(".db_error").hide();
}, 5000);
} //error
});
});
return false;
});
当我单击 ID 为 add_station
的按钮时,它会在 $($this).closest('form').submit(function(){... )
它不起作用,正如你所看到的,我在提交函数之后放置了一个“起作用”的警报。我在控制台上没有收到任何错误,我不知道问题是什么。此外,单击的按钮位于表单内。
我需要在里面使用 $($this).closest('form').submit(function(){...)
因为ajax成功后将使用 add 生成一个新表单将使用此代码的车站按钮。
最佳答案
您应该使用阻止默认提交触发器
e.preventDefault();
$(this).closest('form').submit(function (e) {
e.preventDefault();
<!--rest of the code-->
})
关于javascript - Jquery $(this).closest ('form' );单击按钮后不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26846252/