如何随机运行3个javascript函数中的1个?

时间:2017-07-18 20:27:59

标签: javascript cookies random

我想向页面访问者显示一个随机图像,然后只向同一个访问者显示相同的图像,直到Cookie过期。

一切正常但我仍然坚持初始化。

基本上,如果没有设置cookie,我需要随机运行3个函数中的1个。 我如何随意选择3个函数中的一个并运行它?

$(document).ready(function() {      
var cookie = readCookie("boatColor");
if (!cookie) {
  console.log('Run one of 3 Functions Randomly');
  } else if (cookie == "boatRed") {
    showRedBoat();
  } else if (cookie == "boatWhite") {
    showWhiteBoat();
  } else if (cookie == "boatBlue") {
    showBlueBoat();
  }
}); 


function showRedBoat() {
    var newSrc = ""; 
      var myText = "";
    newSrc = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/500458/copeland_boat_red.jpg"; 
        myText = "<h3>You've got the Red Boat!</h3>";
    theImage.src = newSrc; 
    theDesc.innerHTML = myText;
    createCookie("boatColor", 'boatRed', 0.00034722222);
}

function showWhiteBoat() {
    var newSrc = ""; 
      var myText = "";
    newSrc = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/500458/copeland_boat_white.jpg"; 
        myText = "<h3>You've got the White Boat!</h3>";
    theImage.src = newSrc; 
    theDesc.innerHTML = myText;
    createCookie("boatColor", 'boatWhite', 0.00034722222);
}

function showBlueBoat() {
    var newSrc = ""; 
      var myText = "";
    newSrc = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/500458/copeland_boat_blue.jpg"; 
        myText = "<h3>You've got the Blue Boat!</h3>";
    theImage.src = newSrc; 
    theDesc.innerHTML = myText;
    createCookie("boatColor", 'boatBlue', 0.00034722222);
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;

}

Codepen链接:TPL DataFlow

2 个答案:

答案 0 :(得分:0)

您可以使用new Date().getTime() % 3获取介于0和2之间的伪随机数。然后只需使用switch语句调用一个或多个函数。

答案 1 :(得分:0)

我的解决方案是在没有设置cookie的情况下生成一个随机数,然后根据该数字运行三个函数之一:

$(document).ready(function() {      
  var cookie = readCookie("boatColor");

  if (!cookie) {
    function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  var randomNumber = getRandomInt(0,2);

  if (randomNumber == 0) {
    showRedBoat();
    } else if (randomNumber == 1) {
  showWhiteBoat();
  } else if (randomNumber == 2) {
  showBlueBoat();
  }
      } else if (cookie == "boatRed") {
        showRedBoat();
      } else if (cookie == "boatWhite") {
        showWhiteBoat();
      } else if (cookie == "boatBlue") {
        showBlueBoat();
      }
});