javascript - 如何限制验证码中的两位数字?

标签 javascript jquery security captcha recaptcha

在上面的验证码中,我得到两位数字,即; 0 到 10。但是我希望我的验证码在 0-9 之间。我如何在我的验证码中限制数字 10???是否有任何脚本来停止两位数字?任何帮助,将不胜感激!!

<html>
    <head>
    <title>Captcha</title>

        <script type="text/javascript">

       //Created / Generates the captcha function    
        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 g = Math.ceil(Math.random() * 10)+ '';  
            var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
            document.getElementById("txtCaptcha").value = code
        }

        // Validate the Entered input aganist the generated security code function   
        function ValidCaptcha(){
            var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
            var str2 = removeSpaces(document.getElementById('txtInput').value);
            if (str1 == str2) return true;        
            return false;

        }

        // Remove the spaces from the entered and generated code
        function removeSpaces(string)
        {
            return string.split(' ').join('');
        }


        </script>



    </head>
    <body onload="DrawCaptcha();">
    <table>
    <tr>
        <td>
            Welcome To Captcha<br />
        </td>
    </tr>
    <tr>
        <td>
            <input type="text" id="txtCaptcha" 
                style="background-image:url(1.jpg); text-align:center; border:none;
                font-weight:bold; font-family:Modern" />
            <input type="button" id="btnrefresh" value="Refresh" onclick="DrawCaptcha();" />
        </td>
    </tr>
    <tr>
        <td>
            <input type="text" id="txtInput"/>    
        </td>
    </tr>
    <tr>
        <td>
            <input id="Button1" type="button" value="Check" onclick="alert(ValidCaptcha());"/>
        </td>
    </tr>
    </table>
    </body>
    </html> 

最佳答案

处理随机数时使用 Math.floor()

Math.rand() 返回 0 到 1 之间的数字,但包含 0,而不包含 1。

如果乘以 10,则包含 0,但不包含 10。

这意味着,如果您向上舍入,您将永远不会*得到0结果。

所以,四舍五入;)

*为了得到零,随机选择的数字本身必须恰好为零。从数学上讲,在一系列实数中选取任何精确实数的几率为零,但在实践中,由于计算中数字的限制,这种可能性更大,但仍然不太可能。

关于javascript - 如何限制验证码中的两位数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23655864/

相关文章:

asp.net - 扫描网站漏洞的工具

javascript - 当用户访问页面时如何动态缩放整个 ASP.Net MVC 应用程序

PHP变量到JQuery函数?

javascript - 结合不同变量的两个 if 语句

javascript - D3 v.4 — 比较多个数据集的值

jquery - 带有scroll.depth.js的Google跟踪代码管理器

security - Spring 启动: Full authentication is required to access this resource

security - JSONP 可以安全使用吗?

javascript - rows.sort 不是 rows 是 tr 元素数组的函数

当天指定作者的 JavaScript 名言