2015-04-03 100 views
1

我动态生成capthca代码的动态生成的验证码的代码如下所示如何使固定长度

$(document).ready(function() { 

DrawCaptcha(); 

}); 


    function DrawCaptcha() { 
    var a = Math.ceil(Math.random() * 10) + ''; 
    var b = Math.ceil(Math.random() * 10) + ''; 
    var c = Math.ceil(Math.random() * 10) + ''; 
    var d = Math.ceil(Math.random() * 10) + ''; 
    var e = Math.ceil(Math.random() * 10) + ''; 
    var f = Math.ceil(Math.random() * 10) + ''; 
    var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' ' + f; 
    $(".captha-img")[0].innerHTML = code; 
    } 

所有这些工作正常。

但是现在,我面临的问题是,

我需要的正是6位的Capthcha代码,但有时正在被geenerated的capthacha超过6个位数。

请问我是否知道如何解决这个问题?

http://jsfiddle.net/2yXsL/383/

+0

变化Math.ceil到Math.floor – mohamedrias 2015-04-03 09:26:44

回答

2

变化Math.ceilMath.floor后总是回到你6个数字:

function DrawCaptcha() { 
    var a = Math.floor(Math.random() * 10) + ''; 
    var b = Math.floor(Math.random() * 10) + ''; 
    var c = Math.floor(Math.random() * 10) + ''; 
    var d = Math.floor(Math.random() * 10) + ''; 
    var e = Math.floor(Math.random() * 10) + ''; 
    var f = Math.floor(Math.random() * 10) + ''; 
    var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' ' + f; 
    $(".captha-img")[0].innerHTML = code; 
    } 

与您的代码的问题是,每当Math.random()返航你任何上述9.0它四舍五入它关闭10这就是你有时看到超过6位数字的原因。

+0

这看起来很完美,非常感谢你。 – Kiran 2015-04-03 09:30:56

+0

不客气:) – mohamedrias 2015-04-03 09:31:15

1

可以使用.substring()方法如下所示: -

function DrawCaptcha() { 
    var a = Math.ceil(Math.random() * 10) + ''; 
    var b = Math.ceil(Math.random() * 10) + ''; 
    var c = Math.ceil(Math.random() * 10) + ''; 
    var d = Math.ceil(Math.random() * 10) + ''; 
    var e = Math.ceil(Math.random() * 10) + ''; 
    var f = Math.ceil(Math.random() * 10) + ''; 
    var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' ' + f; 
    $(".captha-img")[0].innerHTML = code.substring(0,12); 
    } 

以上代码将提供一个固定的6位数字作为capthcha代码。

DEMO