我已经说过,标签为<textarea>
的5个文本框。如何随机选择50%的文本框?每个文本框都有不同的ID。例如:
<textarea id = "text1" name= "name1"></textarea>
<textarea id = "text2" name= "name2"></textarea>
<textarea id = "text3" name= "name3"></textarea>
<textarea id = "text4" name= "name4"></textarea>
<textarea id = "text5" name= "name5"></textarea>
我可以在ID上使用某种随机函数吗?
答案 0 :(得分:3)
使用Math.random()
方法生成随机索引。
// get all textarea eleemnts as an array
var $t = $('textarea[id^="text"]').get();
// iterate upto half length
for (var i = 0, len = $t.length / 2; i < len; i++) {
// generate random index and remove it from collection
// where element can be remove using splice method
// and which returns an array of removed elements
// get the elment from that array and update the value or do whatever you are trying to achieve
$t.splice(Math.floor(Math.random() * $t.length), 1)[0].value = i;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text1" name="name1"></textarea>
<textarea id="text2" name="name2"></textarea>
<textarea id="text3" name="name3"></textarea>
<textarea id="text4" name="name4"></textarea>
<textarea id="text5" name="name5"></textarea>
答案 1 :(得分:0)
以有效的方式查看How to get n no elements randomly from an array,从阵列中选择n
随机元素(这将返回唯一元素)。调整此解决方案,您可以执行以下操作:
// https://stackoverflow.com/questions/19269545/how-to-get-n-no-elements-randomly-from-an-array
function getRandom(arr, n) {
var result = new Array(n),
len = arr.length,
taken = new Array(len);
if (n > len)
throw new RangeError("getRandom: more elements taken than available");
while (n--) {
var x = Math.floor(Math.random() * len);
result[n] = arr[x in taken ? taken[x] : x];
taken[x] = --len;
}
return result;
}
var textareas = $('textarea');
var randomTextareas = getRandom(textareas, textareas.length / 2);
randomTextareas.forEach(function(textArea) {
$(textArea).prop('value', 'hello');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text1" name= "name1"></textarea>
<textarea id="text2" name= "name2"></textarea>
<textarea id="text3" name= "name3"></textarea>
<textarea id="text4" name= "name4"></textarea>