为什么我不能让Math.random()和if/else语句的组合工作呢?

Why can't I get this combination of Math.random() and if/else statements to work?

本文关键字:语句 else 组合 工作 if 不能 Math random 为什么      更新时间:2023-09-26

我希望JQuery方法.html根据Math.random()函数生成的值将<img src='file.png'>放入<td>中。if/else语句用于确定添加<img src='file.png'>td

问题是,每当我重新加载页面时,无论Math.random生成什么值,<img src='file.png'>总是添加到#bottom-right

下面是我的代码:

// script.js
$(document).ready(function () {
    var value = Math.random;
    if (value <= 0.1) {
        $("#top-left").html("<img src='file.png'>");
    } else if (value <= 0.2 && value > 0.1) {
        $("#top-middle").html("<img src='file.png'>");
    } else if (value <= 0.3 && value > 0.2) {
        $("#top-right").html("<img src='file.png'>");
    } else if (value <= 0.4 && value > 0.3) {
        $("#middle-left").html("<img src='file.png'>");
    } else if (value <= 0.5 && value > 0.4) {
        $("#middle-middle").html("<img src='file.png'>");
    } else if (value <= 0.6 && value > 0.5) {
        $("#middle-right").html("<img src='file.png'>");
    } else if (value <= 0.7 && value > 0.6) {
        $("#bottom-left").html("<img src='file.png'>");
    } else if (value <= 0.8 && value > 0.7) {
        $("#bottom-middle").html("<img src='file.png'>");
    } else {
        $("#bottom-right").html("<img src='file.png'>");
    }
});
<!-- page.html -->
<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <table border="1px">
            <tr>
                <td class="square" id="top-left"></td>
                <td class="square" id="top-middle"></td>
                <td class="square" id="top-right"></td>
            </tr>
            <tr>
                <td class="square" id="middle-left"></td>
                <td class="square" id="middle-middle"></td>
                <td class="square" id="middle-right"></td>
            </tr>
            <tr>
                <td class="square" id="bottom-left"></td>
                <td class="square" id="bottom-middle"></td>
                <td class="square" id="bottom-right"></td>
            </tr>
        </table>
    </body>
</html>

变化:

var value = Math.random;

:

var value = Math.random();

代替

Math.random 

改为

Math.random()

否则value只是一个函数引用,它总是会击中else语句

您可能还需要将数字四舍五入到小数点后一位