if条件总是返回true

时间:2017-08-16 18:31:14

标签: javascript jquery

请在这里帮忙:if条件总是返回true虽然它是假的? 这些是变量div的html代码,并在开头变量

(<div class="div" id="div" style="background:yellow"></div>) 
(<input type="text" id="your">)

$(document).ready(function generate() {
        "use strict";
        var x = $(".2").text(Math.floor((Math.random() * 10))),
            z = $(".3").text(Math.floor((Math.random() * 10)));

        $(".div").text(x.text() + z.text());
    });



        var show = document.getElementById("show"),
            your = document.getElementById("your").value,
            div = document.getElementById("div").textContent;
        show.onclick = function () {
            "use strict";
            if (your == div) {
                alert("yes");
            } else {
                alert("noo");
            }
        };

1 个答案:

答案 0 :(得分:1)

问题是,您正在定义函数之外的值。因此,在onclick处理程序中,您要比较初始值。

如果您想要实际值,您应该访问函数内的值:

var show = document.getElementById("show"),
    your = document.getElementById("your"),
    div = document.getElementById("div");

show.onclick = function () {
    if (your.value == div.textContent) {
        alert("yes");
    } else {
        alert("noo");
    }
};