js代码,function.js
- function randomAlphanumeric(dstObj,charsLength,chars) {
- var dstElem = document.getElementById(dstObj);
- var length = charsLength;
- if (!chars)
- var chars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789";
- var randomChars = "";
- for(x=0; x<length; x++) {
- var i = Math.floor(Math.random() * chars.length);
- randomChars += chars.charAt(i);
- }
- dstElem.value = randomChars;
- }
使用相当灵活,字符串长度,由哪些字符生成,都可以自定义。
下面是一个生成8位随机密码的调用示例:
- <script src="function.js" type="text/javascript"></script>
- <input id="password" type="text" name="username" value='' tabindex="100" />
- <input type='button', value='Random' class='button' onclick="javascript:randomAlphanumeric('password',8)">
生成6位随机数字:
- onclick="javascript:randomAlphanumeric('password',6, '0123456789')