我目前正在用 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/