【问题标题】:JS Dice - Assigning Math.random value to an html image using if conditionJS Dice - 使用 if 条件将 Math.random 值分配给 html 图像
【发布时间】:2018-08-05 00:19:05
【问题描述】:

您好,我正在使用 Javascript 创建随机骰子输出(从 1 到 6),包括骰子面的图像。
mathRandomDice 函数工作正常,但我将其分配给图像的“if”条件不是...
我的目标是将 Math.random 值分配给图像。

function mathRandomDice() {
    document.getElementById("dice").innerHTML = Math.floor(Math.random() * 6) + 1; 

}

var x = mathRandomDice;

  if (x = 1) {
            d.innerHTML = '<img src=https://image.ibb.co/cQKOhc/dice1.png>';
    }

function mathRandomDice() {
    document.getElementById("dice").innerHTML = Math.floor(Math.random() * 6) + 1; 

}
  body {
    text-align:center;}


/* button */

button {
  display: inline-block;
  padding: 15px 25px;
  font-size: 24px;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  outline: none;
  color: #fff;
  background-color: #4CAF50;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
}

button:hover {background-color: #3e8e41}

button:active {
  background-color: #3e8e41;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}
 <h5> Press the button for a random dice number<h5>
    <span id="yournum"></span>
   <p id="dice"></p>
<button onclick="mathRandomDice()">Roll The Dice</button>
<br><br>
   <img src="https://image.ibb.co/cQKOhc/dice1.png" alt="1" class="center">
   <img src="https://image.ibb.co/cmyG2c/dice2.png" alt="2" class="center">
   <img src="https://image.ibb.co/bPNyFx/dice3.png" alt="3" class="center">
   <img src="https://image.ibb.co/fmkJFx/dice4.png" alt="4" class="center">
   <img src="https://image.ibb.co/d6D5vx/dice5.png" alt="5" class="center">
   <img src="https://image.ibb.co/nFqkvx/dice6.png" alt="6" class="center">

【问题讨论】:

  • 如何设置x?您的功能是否缺少某些东西?也许return 给你编码和审查mathRandomDice()

标签: javascript html image if-statement random


【解决方案1】:

我的问题的解决方法真的很简单..

我的朋友 Corristo 是对的,我写错了“(x = 1)”的真正赋值错误“(x == 1)”

你必须像这样把随机结果放在函数上:

img.src = “骰子”+ 随机 + “.jpg”

这样你就可以为随机数加载正确的图像

随机 == 1 “骰子”+ 随机 + “.jpg” = 骰子1.jpg

随机 == 2 “骰子”+ 随机 + “.jpg” = dice2.jpg

等等..

【讨论】:

    【解决方案2】:

    单个= 是一个赋值运算符。比较使用=====。这应该有效:

    if (x == 1) {
        d.innerHTML = '<img src=https://image.ibb.co/cQKOhc/dice1.png>';
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-03
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多