2009-06-21 140 views
1

我正在查看jQuery文檔here中「click」事件的示例。我可以重構兩個匿名函數如下,它仍然有效:jQuery newbie:如何將參數傳遞給事件處理函數?

$(document).ready(function(){ 
    $("p").hover(hilite, remove_hilite); 
    }); 

    function hilite() 
    { 
    $(this).addClass("hilite"); 
    } 

    function remove_hilite() 
    { 
    $(this).removeClass("hilite"); 
    } 

但是,如果我想一個參數傳遞給hilite什麼?我的第一個猜測是我應該使用一個匿名函數,如this。然而,這似乎並沒有工作,即使我用它不帶參數:

$("p").hover(
    function() 
    { 
     hilite(); 
    } 
    , 
    function() 
    { 
     remove_hilite(); 
    } 
); 

我也試圖重構如下,但這並沒有工作,要麼:

$(document).ready(function(){ 
    $("p").hover(hilite2, remove_hilite); 
    }); 

    function hilite2(){ 
    return hilite(); 
    } 

什麼正確的方法來做到這一點?我覺得我有一個很大的概念誤解。特別是,我不清楚在第一次重構時如何將this對象傳遞給hilite函數。

回答

2

您可以封裝你懸停函數調用到接受了「類名」參數的另一個功能:

$.fn.hoverClass = function(className){ 
    return this.hover(function(){ 
     $(this).addClass(className); 
    }, function(){ 
     $(this).removeClass(className); 
    }); 
} 

然後,你可以通過這個簡單的使用它:

$('p').hoverClass('hilite'); 
0

爲什麼不能簡單地在匿名函數中調用$(this).addClass()方法?

$("p").hover(
    function() { 
    $(this).addClass("hilight"); 
    }, 
    function() { 
    $(this).removeClass("hilight"); 
    } 
); 
+0

是的,這是我鏈接到頁面上的原有功能。我正在嘗試探索如何重構它。在這種情況下,它只是一個單線程,但我預計有複雜的功能,我想存儲在一個單獨的文件,以便我可以在多個網頁中重複使用。這是不可能的嗎? – RexE 2009-06-21 02:25:07

1

我想你想要的是部分功能應用

function partial(func /*, 0..n args */) { 
    var args = Array.prototype.slice.call(arguments, 1); 
    return function() { 
    var allArguments = args.concat(Array.prototype.slice.call(arguments)); 
    return func.apply(this, allArguments); 
    }; 
} 

通過以上功能,現在可以做到以下幾點:

$(document).ready(function(){ 
    var f = partial(hilite, "arg1", "arg2" /*etc...*/); 
    $("p").hover(f, remove_hilite); 
    }); 

參考:How can I pre-set arguments in JavaScript function call? (Partial Function Application)

相關問題