duanne9313 2015-02-10 01:49
浏览 52
已采纳

如何在表单字段输入中生成短的唯一代码?

Hi I have this script that loads a unique code into a form input field on page load. Only it generates a long value. How can I shorten this value to maybe half the size number of characters.

EXAMPLE CODE IT GENERATES: adf4a039-7c9d-4642-94f2-0569910a4a10

SCRIPT

<script>
$(document).ready(function() {
function invoiceid() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x3|0x8)).toString(16);
    });
    return uuid;
};

document.getElementById('invoiceid').onclick = function() {
    document.getElementById('uuid').innerHTML = invoiceid();
};

document.getElementById('uuid').innerHTML = invoiceid();

});

</script>
  • 写回答

3条回答 默认 最新

  • dsam70528 2015-02-10 02:00
    关注

    The XXXXX's are being replaced so the more/less X's you have the bigger/smaller the ID will be generated.

    function invoiceid() {
        var d = new Date().getTime();
        // Remove some of the X's to generate a smaller ID 
    // You can also remove '-' if you don't want the ID formatted in sections
        var uuid = 'xxxx-xxxx4xx'.replace(/[xy]/g, function(c) {
            var r = (d + Math.random()*16)%16 | 0;
            d = Math.floor(d/16);
            return (c=='x' ? r : (r&0x3|0x8)).toString(16);
        });
        document.getElementById('uuid').innerHTML=uuid;
        //return uuid;
    }
     window.onload=invoiceid;
    <div id="uuid"></div><button onclick="invoiceid()">New ID</button>

    Happy coding!

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?