开发者

Simplify jQuery function

I have the following function:

var randomImages = ["bgr1","bgr2","bgr3","bgr4","bgr5"开发者_运维知识库,"bgr6"];
var rndNum = Math.floor(Math.random() * randomImages.length);
$(".myDiv").css({ background: "url(/images/" + randomImages[rndNum] + ".gif)" });

Since all the images have the same name except the last numeric value, can't I simplify this?


var numImages = 6;
var rndNum = Math.floor(Math.random() * numImages) + 1;
$(".myDiv").css({ background: "url(/images/bgr" + rndNum + ".gif)" });


This may seem obvious but if you know how many images you have you could replace randomImages.length with a constant e.g. 5 for arguments sake, then you dont need an array so it would be just one line:

$(".myDiv").css( { background: "url(/images/bgr" + Math.ceil(Math.random() * 5) + ".gif)" } );

Note: math.ceil would be better as then you dont need a +1.


Yes, you can. Note that you might want to define a constant rather than just using the magic number 6, but this is the idea.

var rndNum = Math.floor(Math.random() * 6) + 1;
$(".myDiv").css({ background: "url(/images/bgr" + rndNum + ".gif)" });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜