2013-08-29 74 views
0

我試圖簡化像這樣使用多個變量,如「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); 
+0

不要每安裝一個'mouseout'處理程序ime調用'mouseover'處理程序!正確縮進您的代碼! – Bergi

回答

0

我無法從「runShapes」函數返回一個變量,並通過「swapBackground」函數傳遞它。

您不應該將其退回。你應該只調用swapBackground功能從runShapes這樣的:

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 
    } 
} 

然後調用runShapesdocument is ready - 不要使用window.onload

$(document).ready(runShapes); 

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

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

您可以使用$.each這樣的:

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

請注意,我改變了你的代碼,以便mouseout事件只能被綁定一次。您可能也對hover函數感興趣。

+1

您忘記了轉換爲類選擇器 – Bergi