使用.on-and-click处理程序将事件对象传递给对象内的函数。它似乎没有像我想象的那样工作,所以初始事件.prventDefault()不起作用。由于event.prventDefault()不起作用,提交按钮会自动打开mail.php页面,这显然不是我想要的。如果有人能帮我解决这个问题或引导我朝着正确的方向前进,我将不胜感激。
我的脚本:
(function(){
"strict";
var portfolio = {
email: function(event){
event.preventDefault();
alert("hello people");
var form = $('#contact');
var formMessages = $('#form-messages');
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: 'mailer.php',
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
console.log(response);
// Set the message text.
$(formMessages).html('<p class="success">Message has been sent succesfully! Thank you '+ $('#f_name').val() +', a response will be returned in less than one business day.</p>');
// Clear the form.
$('#f_name').val('');
$('#f_email').val('');
$('#f_message').val('');
$('#f_website').val('');
$('#f_budget').val('');
$('#f_hear').val('');
$('#f_startdate').val('');
$('#f_phone').val('');
form.fadeOut('slow').remove();
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).html('<p>'+data.responseText+'</p>');
} else {
$(formMessages).html('<p>Oops! An error occured and your message could not be sent.</p>');
}
});
},
};
$('body').on('click', '.contact', portfolio.email(event));
当你说:
$('body').on('click', '.contact', portfolio.email(event));
则该事件将被发送到portfolio.email(event)
返回的、当然是无效的任何东西。
只需传递函数名称:
$('body').on('click', '.contact', portfolio.email);