簡體   English   中英

通過函數的參數傳遞數組

[英]Passing an array through a function's parameters

我正在嘗試使用多個變量(例如“ one_a”,“ one_b”等)簡化此類操作:

$(".one_a").mouseover(function(){
    $('.main_box').addClass("one_a");
    });
    $(".one_a").mouseout(function(){
     $('.main_box').removeClass("one_a");
});

這就是到目前為止,我在從“ runShapes”函數返回變量並將其通過“ swapBackground”函數傳遞時遇到麻煩。 任何幫助將不勝感激!

var myShapes=new Array();
    myShapes[0]="one_a";      
    myShapes[1]="one_b";
    myShapes[2]="one_c";

function runShapes(){
    for (var i=0;i<myShapes.length;i++){
    }
    return myShapes[i];
}

function swapBackground(currentShape){
    $(currentShape).mouseover(function(){
        $('.main_box').addClass(currentShape);
    });
    $(currentShape).mouseout(function(){
        $('.main_box').removeClass(currentShape);
    });
}

window.onload = swapBackground("." + runShapes);

您可以這樣使用$.each

$.each(["one_a", "one_b", "one_c"], function(_,shape) {
    $('.'+shape).mouseover(function(){
        $('.main_box').addClass(shape);
    }).mouseout(function(){
       $('.main_box').removeClass(shape);
    });
});

請注意,我更改了代碼,以使mouseout事件僅綁定一次。 您可能還對懸停功能感興趣。

我在從“ runShapes”函數返回變量並將其通過“ swapBackground”函數傳遞時遇到麻煩。

您不應該退貨。 您應該像這樣從runShapes調用swapBackground函數:

function runShapes(){
    for (var i=0;i<myShapes.length;i++){
         swapBackground(myShapes[i]); // don't add the dot here, you won't need
                                      // it for add/removeClass
    }
}

然后,在文檔准備就緒時調用runShapes不要使用window.onload

$(document).ready(runShapes);

順便說一句,您最好使用.hover()安裝處理程序:

function swapBackground(currentShape) {
    $("." + currentShape).hover(function(){
        $('.main_box').addClass(currentShape);
    }, function(){
        $('.main_box').removeClass(currentShape);
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM