如果满足条件,我需要从某个数组中随机获得答案

I need to get a random answer from a certain array if a condition is met

本文关键字:数组 随机 答案 条件 满足 如果      更新时间:2023-09-26

我正在尝试找出一种方法来输入复选框或下拉列表,您可以在其中检查多个项目,然后从选中/选择的项目中单击生成按钮,它将产生一个随机答案,我已经有以下内容,但这意味着我必须以逗号分隔的格式手动输入选项,我不想要! 关于如何实现这一目标的任何想法? 抱歉,如果我听起来很愚蠢, 我是一个新手程序员!

<form method="get" action="/" onsubmit="return false;">
        <fieldset>
            <label>
                Things to pick from&#8230;<br>
                <div style="font: 12px/1.5 helvetica, sans-serif;">Comma-separated list</div>
                <textarea style="width: 400px;height: 100px;" name="things" id="things">Enter your options here..</textarea>
            </label>
        </fieldset>
        <p>
            <input type="button" value="Find my Food" onclick="rnd();">
            <img id="ajax-loader" src="ajax-loader.gif" alt="Picking..."
        </p>
    </form>
<script type="text/javascript">
    var rnd = function () {
        var loader, things;
        loader = document.getElementById('ajax-loader');
        loader.style.display = 'inline';
        things = document.getElementById('things').value;
        things = things.replace(', ', ',');
        things = things.split(',');
        setTimeout(function () {
            var thing;
            loader.style.display = 'none';
            thing = Math.floor(Math.random() * things.length);
            document.getElementById('result').innerHTML = things[thing];
        }, 500);
    };
    </script>
    <h2>Result:</h2>
    <div id="result">Click &#8220;Find My Colour!&#8221;</div>
    </font><br />

提前非常感谢!

这是一个垃圾箱

https://jsbin.com/vamesafafo/1/edit?html,output

我添加了一些您可以呈现的默认选项,也许让用户添加它?它只是为每个选项添加一个复选框,然后在单击按钮时,仅过滤掉复选框,然后随机选择一个。我留下了评论,随时改进它!我只是在 html 中添加了一个div 用于选择,但除此之外,我只是更改了一些 javascript

// Add default choices here
var choices = ['apple', 'orange', 'banana', 'kiwi'];
// cache the choices div
var choicesDiv = document.getElementById('choices');
// Add a checkbox for each choice
choices.forEach(function(choice) {
  choicesDiv.innerHTML += "<input class='things' type='checkbox' value="+choice+" /> " + choice + '<br>';
});
var rnd = function () {
    var loader, things;
    loader = document.getElementById('ajax-loader');
    loader.style.display = 'inline';
    // Slice the nodelist into a real array, and only store things that are checked
    things = slice(document.getElementsByClassName('things'))
               .filter(function(a) {return a.checked});
    setTimeout(function () {
        var thing;
        loader.style.display = 'none';
        thing = Math.floor(Math.random() * things.length);
        // We're pulling the value stored in the html
        document.getElementById('result').innerHTML = things[thing].value;
    }, 500);
};
// utility for turning an array-like (like NodeList) object into an array
function slice(x) {
  return Array.prototype.slice.call(x);
}