2011-01-14 12 views
0

へのリファクタリングのjavascript:私はループに以下を入れることができますどのようにループ

if ($('#s1').attr('checked')){ 
    image(s1, mouseX-s1.width/2+random(-brushSize, brushSize), mouseY-s1.height/2+random(-brushSize, brushSize)); 
    } 
    if ($('#s2').attr('checked')){ 
    image(s2, mouseX-s2.width/2+random(-brushSize, brushSize), mouseY-s2.height/2+random(-brushSize, brushSize)); 
    } 
    if ($('#s3').attr('checked')){ 
    image(s3, mouseX-s3.width/2+random(-brushSize, brushSize), mouseY-s3.height/2+random(-brushSize, brushSize)); 
    } 
    if ($('#s4').attr('checked')){ 
    image(s4, mouseX-s4.width/2+random(-brushSize, brushSize), mouseY-s4.height/2+random(-brushSize, brushSize)); 
    } 
    if ($('#s5').attr('checked')){ 
    image(s5, mouseX-s5.width/2+random(-brushSize, brushSize), mouseY-s5.height/2+random(-brushSize, brushSize)); 
    } 

おかげ

+0

image()関数またはs1、...、s5変数に関するコードをもう提供できますか? – jerluc

+0

変数の代わりに#sの配列を作る - >より簡単に追跡してよりスムーズにする – tekknolagi

+0

次にswitch()ステートメントを使用して配列を参照します – tekknolagi

答えて

0

直接ループにif秒のあなたのシリーズを翻訳する一つの例:あなたはおそらく、より意味のある変数名を使用する必要があります

var sElements = [ s1, s2, s3, s4, s5 ]; // Declare an array so that you can reference the s1..5 variables using a numeric index stored in a variable 

for (var i = 0; i < sElements.length; i++) { // Plain old loop, nothing remotely fancy 
    if ($('#s' + (i + 1)).attr('checked')) { // Note the string concatenation with the number (i + 1) 
     var s = sElements[i]; // Put the ith element into a variable for easier referencing 
     image(s, mouseX - s.width/2 + random(-brushSize, brushSize), mouseY - s.height/2 + random(-brushSize, brushSize)); 
    } 
} 

注 - これはあなたのコードの可読性と保守性を向上します。

1

を私は最も簡単なのは、アクセス(および維持したいすべての要素のための特別なクラスを作成することだと思いますインクリメンタルID)、jQueryの.each()関数を使用します。

だからあなたはあなたが個別に各オブジェクトに対するコールバックとしての画像()関数を添付しなければならない

$('.yourClass:checked').each(function(index) { 
    var my_id = $(this).attr(id); // or use the index 
    image(my_id, mouseX-s5.width/2+random(-brushSize, brushSize), mouseY-s5.height/2+random(-brushSize, brushSize)); 
}); 
+0

申し訳ありませんが、イメージfuntionにmy_idが、配列からデータを取得するためにIDを使用するか、 –

0

ような何かを行います。

$("#id").click(){function() { 
    image(); 
}); 
関連する問題