如何将以下内容放入循环中:
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 :(得分: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));
});
答案 1 :(得分:0)
您应该将image()函数作为每个对象的回调单独附加。
$("#id").click(){function() {
image();
});
答案 2 :(得分: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));
}
}
请注意,您应该使用更有意义的变量名称 - 这将提高代码的可读性和可维护性。