javascript - 如何创建一个 jQuery 选择,它是另一个 jQuery 选择的随机样本?

标签 javascript jquery html

这个问题类似于How to get random element in jquery? ,除了我想要获取 k 个不同的随机采样元素的子集(类似于 Python 的 random.sample ),而不是单个随机选择的元素。

对于数组而不是 jQuery 对象的输入,我想出了以下方法:

function randomSample(arr, k) {
    var arr = arr.slice();      // Work with a copy of the original array
    var samples = [];
    var i;
    for (i = 0; i < k; i++) {
        randomIndex = Math.floor(Math.random() * arr.length);
        samples.push(arr.splice(randomIndex, 1)[0]);
    }
    return samples;
}

我想使这个函数适应输入是 jQuery 对象而不是数组的情况。然而,我正在努力解决这个问题,因为我找不到创建“空”jQuery 对象并向其“推送”元素的方法。

我现在要做的是更改所选元素(通过向其添加类 "yellow"),然后使用 not.(".yellow"重新运行 jQuery 选择器")以便无需更换即可采样。这是一个片段(改编自 https://api.jquery.com/slice/ ):

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>slice demo</title>
  <style>
  div {
    width: 40px;
    height: 40px;
    margin: 10px;
    float: left;
    border: 2px solid blue;
  }
  span {
    color: red;
    font-weight: bold;
  }
  button {
    margin: 5px;
  }
  .yellow {
    background: yellow;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p><button>Turn slice yellow</button>
  <span>Click the button!</span></p>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>

<script>
function colorEm(k) {
  var $div = $("div");
  $div.removeClass("yellow");

  var i;
  for (i = 0; i < k; i++) {
    var $notYetHighlighted = $("div").not(".yellow");
    var start = Math.floor(Math.random() * $notYetHighlighted.length);
    var end = start + 1;
    if (end === $notYetHighlighted.length) {
      end = undefined;
    }
    if (end) {
      $notYetHighlighted.slice(start, end).addClass("yellow");
    } else {
      $notYetHighlighted.slice(start).addClass("yellow");
    }
  }
}

$( "button" ).click( function() { colorEm(3) } );
</script>

</body>
</html>

这种“修改和重新查询”范例是随机采样 jQuery 对象的唯一方法吗?

最佳答案

我将你的脚本重写为 jquery 函数。我认为以后更改它很容易。

/**
 * MyFunction to highliting div
 */
$.fn.myFunctionName = function(e) {
  let num = e.data.num;
  let bgCss = "yellow";
  let elements = $('div');
      elements.removeClass(bgCss); // remove highlight class from all divs


  function doHighlite() {
    let randomSquere = Math.floor(Math.random() * elements.length); // get random element index

    // add class if not exist or try generate next element
    if(!$(elements[randomSquere]).hasClass(bgCss)) {
        $(elements[randomSquere]).addClass(bgCss);
    }
    else {
      doHighlite();
    }
  };

  // highlight desired number of elements
  for(let i=0; i<num;i++) {
    doHighlite();
  }
}


您可以使用参数 num 来运行它

$(".red").on('click', { num: 5 }, $.fn.myFunctionName);

JSFIDDLE DEMO

关于javascript - 如何创建一个 jQuery 选择,它是另一个 jQuery 选择的随机样本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46687737/

相关文章:

javascript - 使用 html 文件作为 Angular 2 中组件的模板

javascript - Android Webview 从过期的缓存中加载资源

javascript - JavaScript 对象 `window.screen.width` 如何在 Ubuntu 10.4 中检测我的 ScreenResolution

javascript - 将来自 API 的数据与 Chart JS 一起使用

javascript - 引导多元素旋转木马一次移动一个元素点击?

javascript - 显示内容的替代方法

html - 如何更改 JupyterLab 中单元格的样式/宽度?

html - jQuery - 用 DIV 跟随光标

asp.net - 用数据库值填充 <ul>

javascript - 单击按钮时使用 JavaScript 或 JQuery 向下滚动