我需要将一个变量传递给我的函数

时间:2013-04-11 03:27:01

标签: javascript jquery

我确信这对你们大多数人来说很简单,但我很难学习这个概念。我只需要一些帮助。我已经评论足以解释发生了什么。谢谢!

//tabNavItem is an anchor link
$(tabNavItem).on("click", function(e){
    var currSlide = $(this).attr("rel");
    console.log(currSlide); // right here the value is equal to the rel of the link i click. this is correct!                   
    slideAnimation(); // i tried slideAnimation.call(currSlide) but got nothing and i tried slideAnimation(currSlide) and got 1 every time
    e.preventDefault();

});

function slideAnimation(){

    allTabs.hide();
    $(".active").removeClass("active");
    $("#" + currSlide).show();                          
    $("." + tabNavClass + " a[rel=" + currSlide + "]").addClass('active');          

    console.log(currSlide); //right now this equals 1, the rel of the first item.

};

3 个答案:

答案 0 :(得分:3)

您必须将该函数声明为实际接受参数,如下所示:

function slideAnimation(currSlide){  

然后您可以在调用时传递参数

slideAnimation(currSlide);

如果您不知道,请注意JavaScript不会尝试确保参数的类型,并且参数不必与传递的值具有相同的名称。

答案 1 :(得分:1)

//Add an argument here
function slideAnimation(item){
    allTabs.hide();
    $(".active").removeClass("active");
    $("#" + item).show();                          
    $("." + tabNavClass + " a[rel=" + currSlide + "]").addClass('active');          
};

//then call it like this 
$(tabNavItem).on("click", function(e){
    var currSlide = $(this).attr("rel");
    slideAnimation(currSlide);
    e.preventDefault();
});

答案 2 :(得分:0)

提示:将参数添加到slideAnimation

function slideAnimation (currSlide){
    // snip
}