[使用jQuery UI可选时如何获得所选项目的列表?

问题描述 投票:1回答:1

我目前正在使用Google Drive之类的PHP构建文件下载,但只是更简单了。因此,就我而言,我有一个包含一些文件的列表。为了摆脱每一行中的下载按钮,我计划使用一个下载按钮和jQuerys可表达函数:

$( "#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>
javascript html jquery jquery-ui
1个回答
0
投票
  • 您可以使用.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>
© www.soinside.com 2019 - 2024. All rights reserved.