javascript - Triggering an alert if the element that is clicked matches the array item in my random function -




i making flexbox grid game. each square has own id. point of game computer think of random square(this randomized array function each square id array element), , if clicked same 1 computer thought of, alert message pops telling you picked right one. otherwise tells wrong.

i cant figure out how link clicked item if else statement can check see if matches random number. have far.

<body onload ="picknumber()">     <div class="container"">         <button id="flex1" onclick="showanswer()"></button>         <button id="flex2" onclick="showanswer()"></button>         ...and on , forth     </div> </body>  function picknumber() {     var grid = ["flex1", "flex2", "flex3", "flex4", "flex5", "flex6", "flex7", "flex8", "flex9"];     var randomnumber = grid[math.floor(math.random() * values.length)]; }  function showanswer() {      if (id.target == randomnumber) {      alert("correct!");      } else {      alert("sorry, try again!");      } } 

the functionality should below , can work out formatting. problems code were:

  1. when set variable within function (like set randomnumber), not accessible outside function. therefore, declare variable outside function first , manipulate function
  2. randomnumber returning number starting 0, id's start 1
  3. id.target == randomnumber - should target.id, target passed on within function - otherwise target not declared anywhere

var boxes = document.getelementsbytagname("div");  for( let i=0, lenn = boxes.length; < lenn; ++ ){    boxes[i].onclick = function() {      var comp_guess = picknumber();      if( boxes[i].id == comp_guess ) {            alert('you win! guessed '+boxes[i].id);      } else {            alert('no candy.');        }    }  }  function picknumber() {      var grid = ["flex1", "flex2", "flex3", "flex4", "flex5", "flex6", "flex7", "flex8", "flex9"];      return grid[math.floor(math.random() * grid.length)];  }
div {    display:inline-block;    width:30px;    height:30px;    border:1px solid #000;    margin:2em;    cursor:pointer;  }
<div id="flex1"></div>  <div id="flex2"></div>  <div id="flex3"></div>  <div id="flex4"></div>  <div id="flex5"></div>  <div id="flex6"></div>  <div id="flex7"></div>  <div id="flex8"></div>  <div id="flex9"></div>





wiki

Comments

Popular posts from this blog

elasticsearch - what is the equivalent data type for geo_point in hibernate search? -

firebase - How to wait value in Ionic 2 -

Jenkins: find build number for git commit -