2015-04-06 65 views
-1

我有這些「功能」在塊中重複的各種元素。 如何簡化使用「var」?簡化函數jquery

謝謝:)

例如:

$('#test1').waypoint(function (direction) { 
    if (direction === 'down') { 
    $(this).addClass("here"); 
    $(this).prevAll().removeClass("here"); 
    $(this).prev().prev().addClass("here_pre"); 
    $(this).next().next().addClass("here_pre"); 
    }, 
}); 

我想在像這樣的一個解決辦法:

var active_here = $(this).addClass("here"), 
        $(this).prevAll().removeClass("here"), 
        $(this).prev().prev().addClass("here_pre"), 
        $(this).next().next().addClass("here_pre"); 

最後記得是這樣的:

$('#test1').waypoint(function (direction) { 
    if (direction === 'down') { 
    active_here; 
    }, 
}); 

$('#test2').waypoint(function (direction) { 
    if (direction === 'up') { 
    active_here; 
    }, 
}); 

etc... etc... etc... 
+0

你問如何編寫自己的功能? – SLaks 2015-04-06 02:22:07

回答

0

JavaScript變量函數(或既可以聲明爲功能正常):

var active_here = function($elem){ 
    $elem.addClass("here"); 
    $elem.prevAll().removeClass("here"); 
    $elem.prev().prev().addClass("here_pre"); 
    $elem.next().next().addClass("here_pre"); 
} 

呼叫:

$('#test1').waypoint(function (direction) { 
    if (direction === 'down') { 
    active_here($(this)); 
    }, 
}); 

$('#test2').waypoint(function (direction) { 
    if (direction === 'up') { 
    active_here($(this)); 
    }, 
}); 
0

你爲什麼不創建一個函數,然後在函數內部調用函數?

function active_here(this) { 
     //code here.. 
} 
+0

在他要調用它的時候,他在函數中將方向作爲參數。那麼「這個」仍然是那個元素?我認爲這不是,但可能是錯誤的。 – 2015-04-06 02:24:59

+0

是的,他可以在這裏是一個鏈接到另一個線程與相同的問題 - > http://stackoverflow.com/questions/7767593/jquery-passing-this-to-a-function – Woody008 2015-04-06 02:29:17

+0

不知道如果我們正在說蘋果蘋果。在那個例子中,這個人明確地將「this」作爲參數傳遞給回調函數。在這個問題中,他的功能需要一個「方向」參數。 – 2015-04-06 02:33:49