结题思路
- 获取随机数
- 创建点击事件
- 判断随机数值输出中奖结果
传统写法
<body>
<h2>传统写法抽奖</h2>
<button id="btn">点击抽奖</button>
<script>
function rand(min, max) {
return Math.round(Math.random() * (max - min) + min)
}
const btn = document.getElementById('btn')
btn.onclick = () => {
var a = rand(1, 100);
if (a<=50) {
console.log("中奖",a)
} else {
console.log("未中奖",a)
}
}
</script>
</body>
promise写法
<body>
<div>
<h2>Promise写法写抽奖</h2>
<button id="btn">点击抽奖</button>
</div>
<script>
function rand(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
const btn = document.getElementById('btn')
btn.onclick = function () {
const p = new Promise((re,rej) => {
var a = rand(1, 100);
if (a <= 50) {
re(a);
} else {
rej(a);
}
})
p.then((res) => { console.log(res,"中奖了") }).catch(rej => { console.log(rej,"未中奖")})
}
</script>
</body>