开发者

Refactor javascript into loop

How can I put the following into a loop:

 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+rand开发者_运维百科om(-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));
    }

Thanks


I think the simplest is to create a special class for every element you want to access (and keep the incremental id) and use the .each() function from jquery.

So you do something like

$('.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));
 });


One example that directly translates your series of ifs into a loop:

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

Note that you should probably use more meaningful variable names -- this will increase the readability and maintainability of your code.


You should attach the image() function as a callback for each object individually.

$("#id").click(){function() {
  image();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜