从dom中挑选一定数量的子元素

时间:2016-11-17 19:49:40

标签: javascript jquery 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个并将它们存储在另一个变量中

4 个答案:

答案 0 :(得分:2)

您只需要生成一个随机数,然后使用该数字作为循环的基础:

&#13;
&#13;
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);
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

我建议的一种方法是使用一个简单的插件:

(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 Fiddle demo

由于上面的大多数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>

参考文献:

参考书目:

答案 2 :(得分:2)

您可以使用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);

答案 3 :(得分:1)

以下示例使用ES6 Map:

&#13;
&#13;
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)
} 
&#13;
<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>
&#13;
&#13;
&#13;