[英]pick certain amount of child elements from the dom
我在页面中有15个带有特定类名的div标签
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
我可以使用jQuery选择它们
var targetDivs = $(' .className ');
在这种情况下,它将返回15个div标签,但我想随机选择仅9个标签并将它们存储在另一个变量中
您只需要生成一个随机数,然后将该数字用作循环的基础即可:
var targetDivs = document.querySelectorAll('.className'); var randomAmount = prompt("What is the upper limit for a random number you want?"); var randomNum = Math.floor(Math.random() * randomAmount); console.log("Random number is: " + randomNum); for(var i = 0; i < randomNum; ++i){ var randomNode = Math.floor(Math.random() * targetDivs.length); console.log("Result includes: " + targetDivs[randomNode].textContent); }
<div class="className">CONTENT 1</div> <div class="className">CONTENT 2</div> <div class="className">CONTENT 3</div> <div class="className">CONTENT 4</div> <div class="className">CONTENT 5</div> <div class="className">CONTENT 6</div> <div class="className">CONTENT 7</div> <div class="className">CONTENT 8</div> <div class="className">CONTENT 9</div> <div class="className">CONTENT 10</div> <div class="className">CONTENT 11</div> <div class="className">CONTENT 12</div> <div class="className">CONTENT 13</div> <div class="className">CONTENT 14</div> <div class="className">CONTENT 15</div>
我建议的一种方法是使用简单的插件:
(function($) {
// naming the new plugin ('getRandom'):
$.fn.getRandom = function(n) {
// creating an Array by passing the jQuery collection
// the 'this' passed to the function to the get()
// method, which takes the passed-in collection
// and returns a jQuery Array:
var collection = this.get(),
// creating an Array, using an Array-literal:
result = [],
// initialising a variable for use, later:
rand;
// converting the passed-in argument, 'n', into a
// base-10 ('10') Number, using parseInt() (this
// does no harm if 'n' is already a Number, but
// ensures that, if a String is passed in ('3' for
// example) we get a Number back out:
n = parseInt(n, 10);
// while n is still truthy (so non-zero):
while (n) {
// we generate a random number in the range of
// 0 to the length of the collection Array:
rand = Math.floor(Math.random() * collection.length);
// we use the random number as an index, and
// push the Array-element at that index in the
// collection Array into the result Array:
result.push(collection[rand]);
// we then remove the element at that index from the
// collection Array, passing in the same index ('rand')
// and deleting one element ('1'):
collection.splice(rand, 1);
// decrement the n variable:
n--;
}
// convert the result Array of elements back into
// object, and return that object to the calling
// context for chaining:
return $(result);
}
})(jQuery);
(function($) { $.fn.getRandom = function(n) { var collection = this.get(), result = [], rand; n = parseInt(n, 10); while (n) { rand = Math.floor(Math.random() * collection.length); result.push(collection[rand]); collection.splice(rand, 1); n--; } return $(result); } })(jQuery); $('.className').getRandom(10).css({ 'opacity': '0.2' })
.className { display: inline-block; width: 3em; height: 3em; box-sizing: border-box; border: 2px solid #000; text-align: center; overflow: hidden; counter-increment: boxCounter; position: relative; } .className::after { content: counter(boxCounter, decimal-leading-zero); position: absolute; top: 0; left: 0; bottom: 0; right: 0; background-color: #fff; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div>
JS小提琴演示 。
由于上面的大多数jQuery插件都是用纯JavaScript编写的,因此,即使使用纯JavaScript,这当然也很容易实现,尽管它是函数,而不是方法或原型扩展(尽管如果您希望这样做) ,这样做仍然很容易,尽管不一定建议这样做):
function getRandomFrom(haystack, n) {
// ensuring that we have an Array, assuming we're
// passed an Array-like Object (such as a NodeList,
// HTMLCollection or, even, an Array):
haystack = Array.from(haystack);
// ensuring that the variable n is a Number, using
// parseInt():
n = parseInt(n, 10);
// creating an empty Array:
var result = [],
// initialising a variable for later use:
rand;
// while n is truthy (non-zero):
while (n) {
// we generate a random number between 0 and
// the Array-length:
rand = Math.floor(Math.random() * haystack.length);
// we use the random number as an index for the Array,
// and push the Array-element held at that index to the
// result Array:
result.push(haystack[rand]);
// we remove that Array-element from the Array, using
// Array.prototype.splice():
haystack.splice(rand, 1);
// decrement n, to ensure we don't have an infinite
// while loop:
n--;
}
// return the result Array to the calling context:
return result;
}
function getRandomFrom(haystack, n) { haystack = Array.from(haystack); n = parseInt(n, 10); var result = [], rand; while (n) { rand = Math.floor(Math.random() * haystack.length); result.push(haystack[rand]); haystack.splice(rand, 1); n--; } return result; } var elems = document.querySelectorAll('.className'); getRandomFrom(elems, 5).forEach(el => el.classList.add('selected'));
.className { display: inline-block; width: 3em; height: 3em; box-sizing: border-box; border: 2px solid #000; text-align: center; overflow: hidden; counter-increment: boxCounter; position: relative; } .className::after { content: counter(boxCounter, decimal-leading-zero); position: absolute; top: 0; left: 0; bottom: 0; right: 0; background-color: #fff; } .className.selected { opacity: 0.25; border-color: red; }
<div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div> <div class="className">CONTENT</div>
参考文献:
css()
。 参考书目:
您可以使用Jquery Each并构建唯一且随机的元素数组。
然后,您可以在元素数组上循环播放,以将元素放置在您希望此随机化发生的位置。
var divs = [];
var indexs = [];
while(indexs.length < 9){
var num = Math.floor(Math.random() * 9) + 1;
indexs.push(num);
indexs = $.unique(indexs);
}
$('.className').each(function(index, element){
if(indexs[index]){
divs.push($('.className').eq(indexs[index]));
}
});
console.log(divs);
以下使用ES6 Map的示例:
let results = new Map(); for(let i = 0; i < 9; i++) { let index= null; while(index=== null || results.has(index)) { index= Math.floor(Math.random() * 9); } results.set(index, document.querySelectorAll('.className')[index]); } for (let result of results.values()) { console.log(result.textContent) }
<div class="className">CONTENT 1</div> <div class="className">CONTENT 2</div> <div class="className">CONTENT 3</div> <div class="className">CONTENT 4</div> <div class="className">CONTENT 5</div> <div class="className">CONTENT 6</div> <div class="className">CONTENT 7</div> <div class="className">CONTENT 8</div> <div class="className">CONTENT 9</div> <div class="className">CONTENT 10</div> <div class="className">CONTENT 11</div> <div class="className">CONTENT 12</div> <div class="className">CONTENT 13</div> <div class="className">CONTENT 14</div> <div class="className">CONTENT 15</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.