我的代码
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())
相同,但我不能
答案 0 :(得分: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!");
}
});