好的,非常直接的JQuery问题,我正在努力寻找答案:
我有一个在按钮点击时调用的JQuery事件:
$(document).ready(function(){
resetForms('reservation');
$('#form-reservation').submit(function(event){
event.preventDefault(); //the page will no longer refresh on form submit.
var resCheck = $(this).find('input[class="reservationid"]').val(); //now we have the reservation ID, let's perform our check.
document.cancel_res.cancel_agree.checked = false;
//document.cancel_res.cancel_agree.disabled = false;
document.cancel_res.cancel_button.disabled=true;
document.form_reservation.search_button.value="Searching...";
document.form_reservation.search_button.disabled=true;
$.ajax({
url: 'inc/searchres.php',
type: 'POST',
data: 'resid='+resCheck,
success: function(data){ //data is all the info being returned from the php file
resetForms('reservation'); //clear forms
document.form_reservation.search_button.value="Search Reservation";
document.form_reservation.search_button.disabled=false;
$('#reservation-id').val(resCheck); //add read ID back into text box
var jsonData = $.parseJSON(data);
//BLAH BLAH BLAH BLAH
}
});
});
});
该功能完美无缺......但是,无论如何在不使用提交事件的情况下调用此函数?我尝试在$('#form-reservation').submit(function(event){
调用后取出所有内容并将其放在一个单独的函数中,然后从submit事件中调用该函数。然而,无论出于何种原因,这都失败了。
基本上,我希望提交事件仍然触发此功能,但我也希望能够在其他情况下调用整个函数。提前谢谢!
答案 0 :(得分:2)
实际上非常简单:
var MyFunc = function(event){
typeof event !== 'undefined' ? event.preventDefault() : false; //the page will no longer refresh on form submit.
var resCheck = $(this).find('input[class="reservationid"]').val(); //now we have the reservation ID, let's perform our check.
document.cancel_res.cancel_agree.checked = false;
//document.cancel_res.cancel_agree.disabled = false;
document.cancel_res.cancel_button.disabled=true;
document.form_reservation.search_button.value="Searching...";
document.form_reservation.search_button.disabled=true;
$.ajax({
url: 'inc/searchres.php',
type: 'POST',
data: 'resid='+resCheck,
success: function(data){ //data is all the info being returned from the php file
resetForms('reservation'); //clear forms
document.form_reservation.search_button.value="Search Reservation";
document.form_reservation.search_button.disabled=false;
$('#reservation-id').val(resCheck); //add read ID back into text box
var jsonData = $.parseJSON(data);
//BLAH BLAH BLAH BLAH
}
}
$(document).ready(function(){
resetForms('reservation');
$('#form-reservation').submit(MyFunc); //this calls on submit
});
//this calls without need of a submit
MyFunc();
答案 1 :(得分:1)
我只是触发处理程序。
$("#form-reservation").triggerHandler("submit");
http://api.jquery.com/triggerHandler/
根据api文档,这不会导致表单提交,它只是运行绑定到该事件的处理程序。