如果满足条件,我需要从某个数组中随机获得答案
I need to get a random answer from a certain array if a condition is met
我正在尝试找出一种方法来输入复选框或下拉列表,您可以在其中检查多个项目,然后从选中/选择的项目中单击生成按钮,它将产生一个随机答案,我已经有以下内容,但这意味着我必须以逗号分隔的格式手动输入选项,我不想要! 关于如何实现这一目标的任何想法? 抱歉,如果我听起来很愚蠢, 我是一个新手程序员!
<form method="get" action="/" onsubmit="return false;">
<fieldset>
<label>
Things to pick from…<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 “Find My Colour!”</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);
}
相关文章:
- Jquery/Javascript:通过按下按钮显示数组中的随机图像
- Javascript-从随机的单词数组中创建段落
- JavaScript-从对象数组中输出随机OBJECT
- 数组中的随机文本字符串
- Javascript从数组中随机选择并按字母顺序排列
- 如何在数组javascript中选择伪随机值
- 从数组中随机抽取的最佳方式
- 在两个位置显示数组中的随机单词
- 从数组中随机采样子集
- Javascript - 如何按顺序从数组中挑选随机元素
- Javascript 数组随机丢失一个元素
- Javascript从数组中选择一个随机对象集
- 如何从包含1000个项目的数组中随机选择一个项目
- 从数组中随机选择项,仅在以前未使用过时使用
- 从数组随机重定向URL
- 从数组随机项-不能找到变量:getElementById
- 二维数组随机生成器
- 从零重复的数组随机生成名称
- Javascript数组随机得到零
- 数组随机返回的茉莉测试