是否可以使用另一个按钮告诉我最后一次警报?

时间:2013-04-23 22:19:21

标签: javascript string button random alert

我希望有两个按钮,一个自动在警报中生成随机字符串,我希望其他用户能够在文本框中输入代码并告诉他们是否有效。

首先这可能吗?第二,对于刚接触JavaScript的人来说这很难吗?

这是我现在正在使用的当前代码。

<script language="javascript" type="text/javascript">
function randomString() {
 var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
 var string_length = 5;
 var randomstring = '';
 for (var i=0; i<string_length; i++) {
  var rnum = Math.floor(Math.random() * chars.length);
  randomstring += chars.substring(rnum,rnum+1);
 }
 return randomstring;
}
</script>

<script>
function myFunction()
{
alert(randomString());
}
</script>

Thanks1

1 个答案:

答案 0 :(得分:1)

那个怎么样:

----------- file:index.html -----------

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Captcha Test</title>
    <script src="test.js"></script>
</head>
<body onload="loadCaptcha('captcha-region')">

    <div id="captcha-region"
         style="text-indent: 10px; background: #fffccc"></div>

    <label for="captcha"> Re-type text: </label>
    <input  id="captcha" type="text" value="" />

    <input type="button" value="Submit"
           onclick="checkCaptcha('result-region')" />

    <input type="button" value="Reload"
           onclick="loadCaptcha('captcha-region')" />

    <div id="result-region"></div>

</body>
</html>

--------- file:test.js -----------------

function randomInt (range) {
    return Math.floor(Math.random() * range);
}

function randomPos (s) {
    return randomInt(s.length);
}

function randomChar (s) {
    return s.charAt(randomPos(s));
}


var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";

function randomString () {
    var s = '',
        i = 0;

    while (i++ < 5) {
        s += randomChar(chars);
    }

    return s;
}

function htmlInsert (id, htmlData) {
    document.getElementById(id).innerHTML = htmlData;
}


var captcha;

function loadCaptcha (captchaRegion) {
    captcha = randomString();

    htmlInsert(captchaRegion, '<h1>' + captcha + '</h1>');
}

function checkCaptcha (resultRegion) {
    var okText = (captcha === document.getElementById('captcha').value)
            ? '<span style="color: yellowgreen"> ok </span>'
            : '<span style="color: orange">  not ok </span>';

    htmlInsert(resultRegion, '<h2>Typed text: ' + okText + '</h2>');
}

这基本上是有点验证码演示,也许包含一些好的部分..

您可能想要放置index.html&amp; test.js在你喜欢的目录中(不需要本地的web服务器),然后从那个目录里面执行:“firefox index.html”,你很高兴..

您怎么看?