gpt4 book ai didi

javascript - 如何在选择下拉列表中随机选择以前在 JavaScript 中未选择的项目?

转载 作者:行者123 更新时间:2023-12-02 21:22:22 25 4
gpt4 key购买 nike

单击按钮时,我想运行一个函数,每次都会从选择下拉列表中随机选择一个以前未选择的选项。如果选择了所有选项,我想重置使用的选项并从头开始。

我有一个函数,可以从数组中随机选择一个之前未选择的元素(credit 到 @Rajesh)

function randomize(arr) {
let data = [...arr];
let chosenItems = [];

function getRandomValue() {
if (data.length === 0) {
data = chosenItems;
chosenItems = [];
}
const index = Math.floor(Math.random() * data.length);
const choice = data.splice(index, 1)[0];

chosenItems.push(choice);
return choice;
}

return {
randomItem: getRandomValue
}
}

const dummyData = [ 1,2,3,4,5 ];

const randomizeData = randomize(dummyData);

for (let i = 0; i< 10; i++) {
console.log(randomizeData.randomItem())
}

我已经创建了一个脚本,可以从 select2 下拉列表中随机选择一个元素,但它经常选择相同的元素。

var optionsArray = new Array();
var first = $('select option')[0];
$('select option').each(function () { optionsArray.push(this) });

if (optionsArray.length > 1) {
$('select').html('');

var i = 0;

var random

while (i < optionsArray.length) {

random = Math.floor(Math.random() * optionsArray.length)
//if element hasn't been marked as "selected"
if (optionsArray[random] != "selected") {
$("select").append(optionsArray[random]);
//mark element as selected
optionsArray[random] = "selected"
i++
}
}

var newSelectedOption = $('select option')[0];
$('select').val($(newSelectedOption).val()).trigger('change');

最佳答案

<html>
<body>
<select id="dropdown">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button id="btn">
Generate
</button>
</body>
<script>
let dropdown = document.getElementById('dropdown');
var options = [];
var chosenItems = [];
function setOptions(){
for(var i = 0; i < dropdown.options.length; i++)
options.push(dropdown.options[i].value);
}
document.getElementById('btn').addEventListener("click", function(){
options = options.filter( function( el ) {
return chosenItems.indexOf( el ) < 0;
});
if(options.length == 0){
console.log("reset data")
setOptions();
chosenItems = [];
}
var unSelectedRandom = options[Math.floor(Math.random() * options.length)]
for(var i = 0; i < dropdown.options.length; i++){
var current = dropdown.options[i]
if ( current.value == unSelectedRandom ) {
dropdown.selectedIndex = i;
chosenItems.push(current.value);
console.log("chosen: "+chosenItems)
}
}
});
</script>
</html>

关于javascript - 如何在选择下拉列表中随机选择以前在 JavaScript 中未选择的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60812636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com