2015-04-03 105 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