<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>獲取uuid的三種方式</title>
<script src="../../js/jquery-3.1.1.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
</head>
<body>
<button onclick="getuuid()">uuid</button>
<span id="result"></span>
</body>
<script type="text/javascript">
function getuuid() {
UUid1()
.then(UUid2())
.then(UUid3())
.catch(function (err) {
console.error(err);
});
}
//第一種
function UUid1() {
return new Promise(function (resolve, reject) {
var aaa =('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}));
if(aaa){
alert("UUID1值=="+aaa);
resolve();
}else {
reject("獲取UUID1值失敗");
}
});
}
//第二種
function UUid2() {
return new Promise(function (resolve, reject) {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
var ccc = (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
alert("UUID2值=" + ccc);
if (ccc == null) {
resolve();
}
else {
reject("獲取UUID2值失敗");
return;
}
});
// return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
//第三種
function UUid3() {
return new Promise(function (resolve, reject) {
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
if(uuid){
alert("UUID3值=="+uuid);
resolve();
}else {
reject("獲取UUID3值失敗");
}
});
}
</script>
</html>