【问题标题】:pick certain amount of child elements from the dom从 dom 中挑选一定数量的子元素
【发布时间】:2017-04-01 12:29:27
【问题描述】:

例如,我在一个页面中有 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 个并将它们存储在另一个变量中

【问题讨论】:

  • 您可以将$(' .className '); 的结果存储在一个数组中并从中随机选择元素
  • @empiric 15 div 标签将在数组中??
  • @Mahi 是的,为什么会有问题?
  • @empiric "Array-like" 对象不实现Array.prototype 的完整接口,您应该非常小心不要将它们视为真正的数组。它们将具有length 属性并且可以迭代,它们甚至可以支持一些 Array.prototype 成员,但它们不会支持所有成员。

标签: javascript jquery dom


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    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>

    【讨论】:

      【解决方案3】:

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

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

      参考资料:

      参考书目:

      【讨论】:

        【解决方案4】:

        下面使用 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>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-26
          相关资源
          最近更新 更多