Help us understand the problem. What is going on with this article?

画像をランダムで表示させる

More than 3 years have passed since last update.

仕様

ロードの度に表示される画像がランダムで切り替わるようにしたい。

js

js
var randomImg = function () {
    var $target = $('[data-randomimg]'),
        //表示させたい画像の個数を配列に入れる
        ary = [1,2,3], 
        //ランダムで配列内の数字を取得
        i = ary[Math.floor(Math.random() * ary.length)],
        src;
    if(!$target.length) return;
    src = 'img/img_' + i + '.gif';
    $target.attr('src',src);
};

$(function () {
    randomImg();
});

まとめ

わざわざ配列に画像の個数を入れるのがなんとも。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした