javascript - 使用 jQuery UI 可选择时如何获取所选项目的列表?

标签 javascript html jquery jquery-ui

我目前正在用 PHP 构建一个文件下载,就像 Google Drive 一样,但只是更简单的一种方式。所以就我而言,我有一个包含一些文件的列表。为了摆脱每行中的下载按钮,我计划使用单个下载按钮和 jQuery 可选择的函数:

$( "#storage-files-table" ).selectable();

现在我可以选择单行或多行。当我现在按下下载按钮时,我想获取所有选定元素的列表,以便我现在应该提供哪个文件供下载。有谁知道我怎样才能完成这件事?

jQuery(document).ready(function($) {
  $("table").selectable();
});

function download() {
  //Here I want to get a list of all selected rows
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="download()">Download</button>
<table>
  <thead>
    <th>col1</th>
    <th>col2</th>
    <th>col3</th>
  </thead>
  <tbody>
    <tr>
      <td>a1</td>
      <td>a2</td>
      <td>a3</td>
    </tr>
    <tr>
      <td>b1</td>
      <td>b2</td>
      <td>b3</td>
    </tr>
    <tr>
      <td>c1</td>
      <td>c2</td>
      <td>c3</td>
    </tr>
  </tbody>
</table>

最佳答案

  • 您可以使用 .find("tr.ui-selected") 查找所选元素。
  • 此外,如果您打算选择,请不要忘记使用tbody作为您的选择者。
  • jQuery 库应该领先于 jQuery-UI 库,因此请确保首先调用 jQuery,然后调用它的 UI 扩展。
  • 停止使用内联处理程序 JS。调试和跟踪错误很困难。 JS应该集中在一处,而不是分散在HTML文件中。

jQuery(function($) {

  const $tbody = $("#myTable tbody");
  
  function download() {
    //Here I want to get a list of all selected rows
    const $trSelected = $tbody.find("tr.ui-selected");
    // Collect data-file-id values
    const IDs = $trSelected.get().map(tr => tr.dataset.fileId);
    console.log( IDs );
  }

  $tbody.selectable();
  $("#download").on('click', download);

});
.ui-selected td {
  background: #0bf;
}
<button id="download">Download</button>
<table id="myTable">
  <thead>
    <th>col1</th>
    <th>col2</th>
    <th>col3</th>
  </thead>
  <tbody>
    <tr data-file-id="a595">
      <td>a1</td>
      <td>a2</td>
      <td>a3</td>
    </tr>
    <tr data-file-id="b456">
      <td>b1</td>
      <td>b2</td>
      <td>b3</td>
    </tr>
    <tr data-file-id="c753">
      <td>c1</td>
      <td>c2</td>
      <td>c3</td>
    </tr>
  </tbody>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

关于javascript - 使用 jQuery UI 可选择时如何获取所选项目的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62219060/

相关文章:

javascript - ng-init 调用向 ng-repeat 提供数据的函数

Javascript/HTML5 - Canvas 获取选定对象的尺寸

javascript - 带有手动控件的 slider 不会自动播放 - 可能是 setInterval 行为的问题?

javascript - Highcharts => 点击折线图时获取点的id

javascript - 在 React Native 中删除数组中数量为 0 的项目

javascript - Accordion 菜单 JQuery - 如何打开特定的 "id"?

javascript - 使用跨域站点但相同位置的 JS 文件在子 iFrame 中调用 Javascript 函数

javascript - WordPress 中的 jQuery。未捕获的类型错误 : undefined is not a function

javascript - Jquery 显示隐藏在列表中无法正常工作

javascript - 下拉菜单仅在移动设备上闪烁并消失