要求:总共10个奖项,一等奖一个,二等奖2个,三等奖3个依次类推,抽中后,相应的奖项去除
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id='randomNum'></div>
<div id="buttons" style="border: 1px solid #eee; padding: 6px; width: 50px; height: 16px; border-radius: 10px; display: flex; justify-content: center; align-items: center;">抽奖</div>
</body>
<script>
let dataList = [
{
id: 0,
type: 1,
title: '一等奖'
},
{
id: 1,
type: 2,
title: '二等奖'
},
{
id: 2,
type: 3,
title: '三等奖'
},
{
id: 3,
type: 4,
title: '四等奖'
},
{
id: 4,
type: 5,
title: '五等奖'
},
{
id: 5,
type: 6,
title: '六等奖'
},
{
id: 6,
type: 7,
title: '七等奖'
},
{
id: 7,
type: 8,
title: '八等奖'
},
{
id: 8,
type: 9,
title: '九等奖'
},
{
id: 9,
type: 10,
title: '安慰奖'
}
]
let selectData = {}
let ranData = []
let sum = 0
let ranSums = 0
window.onload = function () {
initData()
}
initData = function () {
sum = 0
ranSums = 0
if (dataList.length) {
if (selectData.length) {
let selectDone = dataList.findIndex(items => item.id == selectData.id)
dataList[selectDone].type = dataList[selectDone].type - 1
if (dataList[selectDone].type == 0) {
dataList.splice(selectDone, 1)
}
selectData = {}
}
dataList.forEach((item) => {
ranSums = ranSums + item.type
})
dataList.map((item, index) => {
sum = sum + item.type
item.randMaxNum = sum
if (index == 0) {
item.randMinNum = item.type
} else {
item.randMinNum = dataList[index - 1].randMaxNum + 1
}
})
}else{
let randomText = document.getElementById('randomNum')
randomText.innerHTML = '奖项已全部抽完'
}
}
document.getElementById("buttons").onclick = function () {
raffleAlgorithm()
};
raffleAlgorithm = function () {
let random = null
random = Math.floor(Math.random() * ranSums) + 1
dataList.forEach((item, index) => {
console.log(item)
if (random >= item.randMinNum && random <= item.randMaxNum) {
console.log(item, 'item--', item.title)
selectData = item
let randomText = document.getElementById('randomNum')
randomText.innerHTML = item.title
initData()
}
})
}
</script>
</html>