我希望我的代码尽可能保持干燥,并且想知道以下是否可行。 我需要多次重复使用下面的代码,唯一的区别是我在下面的函数中所做的事情。
.on("click", "a", function(e) {})
我可以复制 addToBooking 函数,给它一个不同的名称,在点击处理程序中进行轻微的更改,但这感觉既浪费又重复。
我可以将代码块传递给 addToBooking 函数吗? 或者也许还有另一种我不知道的很酷、有效的方法。
完整的代码块
var addToBooking = function(that, event) {
var left, top;
event.stopPropagation();
//Turn off all calendar tracking
$(".track").off();
//Get proper sticky positioning (Checks to make sure it wont display off screen)
left = getPosition(".add_to_booking", "left");
top = getPosition(".add_to_booking", "top");
//Position sticky, display and listen for click event to see what to do next
$(".add_to_booking").css({top: top, left: left})
.fadeIn('fast')
.on("click", function(e) { e.stopPropagation(); })
.on("click", "a", function(e) {
if($(this).text() === "YES") {
//Close dialog
closeTT();
//Open new add to booking box
addBooking(that, event);
} else {
closeTT();
}
});
}
最佳答案
传入函数并赋值
var addToBooking = function(that, event, custFnc) {
...
...
.on("click", "a", custFnc );
}
传递参数需要使用call()
jQuery( function(){
function hey(evt, test){
var text = jQuery(this).text();
alert(text + ":" + test);
}
function addClick( custFnc ){
var test=99;
jQuery("#foo").on("click",
function(e){
custFnc.call(this, e,test);
}
);
}
addClick(hey);
});
Fiddle
关于javascript - jQuery 重构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9406871/