【发布时间】:2014-05-04 12:28:14
【问题描述】:
我在 jQuery 中有两个函数:
$(document).on('change','.states',function(){
//on change of select
});
$(document).on('click','.date_control',function(){
//on click of input .date_control
});
如何将上述两个函数组合成一个函数,以便我可以将它与我的 AJAX 函数一起使用,如下所示:
$(function() {
$(".add_new_rebate").on("click", function(event) {
event.preventDefault();
var manufacturer_id = $("#company_id").val();
/*if($.active > 0) { //or $.active
request_inprogress();
} else {*/
var next_rebate_no = $('.rebate_block').length + 1;
var rebate_no = $('.rebate_block').length + 1;
if ($('.rebate_block').length>0) {
rebate_no = rebate_no+1;
}
$('.add_new_rebate').attr('disabled','disabled');
//}
$.ajax({
type: "POST",
url: "add_rebate_by_product.php",
data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},
beforeSend: function() {
$('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
},
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
}
$('.load').remove();
}
});
});
});
如果您除了将上述两个功能合二为一之外,还有其他方法,那也可以。我的要求是将这两个函数的代码合并到上面的 AJAX 函数中,因为我正在动态生成两个 HTML 控件并且我想将 jQuery 类应用于它们。提前致谢。
【问题讨论】:
-
为什么不将操作(
click中的所有内容)设为函数并从两个事件处理程序中调用它? -
@xFortyFourx:我没有清楚地理解你的想法,但听起来它可能会奏效。请您发布您的答案,以便我了解您的意思吗?
-
这个怎么样?使用通用函数,然后在
click和change时调用它。例如我们使用class。$(document).on('change','.states',function(){ //on change of select commonFunction(); }); $(document).on('click','.date_control',function(){ //on click of input .date_control commonFunction(); });
标签: javascript jquery ajax function jquery-on