0

我的演示 Jsfiddle

我的代码

html

<canvas id="random" title="Click to Change"></canvas>
<input name="rand" type="text" id="rand" data-filter="false"/>
<span id="rands"></span>

jQuery

function Random() {
        var length = 6,
            charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
            retVal = "";
        for (var i = 0, n = charset.length; i < length; ++i) {
            retVal += charset.charAt(Math.floor(Math.random() * n));
        }
        return retVal;
    }
    var ctx = document.getElementById("random").getContext('2d');
    ctx.font = "50px Arial";
    ctx.fillText(Random(), 0, 40);


$("#random").click(function () {
    if($("#rand").val() !== Random()){
    ctx.clearRect ( 0,0,1000,1000 );
    ctx.fillText(Random(), 0, 40);
    }
});



$('#rand').bind('keypress keyup change', function () {
        if ($(this).val() !== Random()) {
            $(this).addClass('false').removeClass('true').attr('data-filter', 'false'), $("#" + this.id + "s").css({
                "color": "#C41111"
            }).text("Characters in conflict with each other!");
        } else {
            $(this).addClass('true').removeClass('false').attr('data-filter', 'true'), $("#" + this.id + "s").css({
                "color": "#7FAC25"
            }).text($(this).val() + " is accepted!");
        }
    });

我想要平等,if($("#rand").val() !== Random())但我不能?

4

1 回答 1

0

每当您调用 Random() 时,都会生成一个新值。所以,当你在这里比较时if ($(this).val() !== Random())

它正在与一个新值进行比较。这就是为什么他们几乎永远不会平等!

var Deli = {
    randomDeger:false,
    random:function() {
        var length = 6,
            charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
            retVal = "";
        for (var i = 0, n = charset.length; i < length; ++i) {
            retVal += charset.charAt(Math.floor(Math.random() * n));
        }
        this.randomDeger = retVal;
        return retVal;
    }
}

    var ctx = document.getElementById("random").getContext('2d');
    ctx.font = "50px Arial";
    ctx.fillText(Deli.random(), 0, 40);


$("#random").click(function () {
    if($("#rand").val() !== Deli.randomDeger){
    ctx.clearRect ( 0,0,1000,1000 );
    ctx.fillText(Deli.random(), 0, 40);
    }
});



$('#rand').bind('keypress keyup change', function () {
        if ($(this).val() !== Deli.randomDeger) {
            $(this).addClass('false').removeClass('true').attr('data-filter', 'false'), $("#" + this.id + "s").css({
                "color": "#C41111"
            }).text("Characters in conflict with each other!");
        } else {
            $(this).addClass('true').removeClass('false').attr('data-filter', 'true'), $("#" + this.id + "s").css({
                "color": "#7FAC25"
            }).text($(this).val() + " is accepted!");
        }
    });
于 2014-02-07T01:17:22.020 回答