2

へー!

私はこのコードを持っています(ほんの一例):

function random(min, max) {
    return min + parseInt(Math.random() * (max-min+1));
}
function getKey(length, charset) {
    var key = "";
    while(length--) {
        key += charset[random(0, charset.length-1)];
    }
    return key;
}
$(document).ready(function() {
    var key = getKey(16, "0123456789ABCDEF");
});

そして、これ ( javascript ) をinput[type="submit"]-form ( html )に「リンク」したい。したがって、ボタンをクリックすると、毎回新しい「キー」が生成されます。

私と一緒に解決策を見つけてください。:-)

4

4 に答える 4

2

このコードを試してください

<html>
<head>
    <script>
        function random(min, max) {
            return min + parseInt(Math.random() * (max - min + 1));
        }

        function getKey(length, charset) {
            var key = "";
            while (length--) {
                key += charset[random(0, charset.length - 1)];
            }
            return key;
        }
        $(document).ready(function () {
            $('#ipt').click(function () {
                var key = getKey(16, "0123456789ABCDEF");
                alert(key);
            });
        });
    </script>
</head>

<body>
    <input type="button" id="ipt" />
</body>
</html>
于 2013-08-24T20:02:46.273 に答える
1

new_keyHTMLコードにID付きのボタンを作成します

 <button id="new_key" type="button">New key!</button> 

そしてあなたのJavaScriptコード

function random(min, max) {
    return min + parseInt(Math.random() * (max-min+1));
}
function getKey(length, charset) {
    var key = "";
    while(length--) {
        key += charset[random(0, charset.length-1)];
    }
    return key;
}
$(document).ready(function() {
    var key = getKey(16, "0123456789ABCDEF");

    $( '#new_key' ).click( function(){
        key = getKey(16, "0123456789ABCDEF");
        alert( key );
    });
});

デモ: http://jsfiddle.net/nohponex/JECWC/2/

于 2013-08-24T20:02:11.870 に答える
1

JSFiddle デモ

getKeyこれは、読みやすくするために名前を変更した からの戻り値を更新するために、少し jQuery を使用しgenerateKeyます。

新しい追加コード:

function getNewKey() {
    $('#key').text(generateKey(16, "0123456789ABCDEF"));
}
$(document).ready(function() {
    getNewKey();
    $('form').on('submit', function(ev){
        getNewKey();
        return false;
    });
});
于 2013-08-24T20:07:49.703 に答える