查找选中复选框的 table 行的索引

Finding index of table rows with checked checkbox

我有一个 html table,其中每行的第一个单元格包含一个复选框。我想通过选中的复选框获取每一行的索引。我可以访问 JQuery 作为 js/$

这是我目前所拥有的,但它只是 returns Javascript 个对象,我无法从中提取索引。

(-> (js/$ "#table tr")
    (.has ":checkbox:checked")
    (.find "td:eq(1)")
    (.each (fn [e] (.text (js/$ e)))))

我不熟悉问题中的语法,但是这段 jquery 代码应该很容易翻译过来。

$("button").on("click", function() {
  var trs = $("input:checked").closest("tr"); //get tr elements of checked inputs
  var indexes = $.map(trs, function(tr) { return $(tr).index(); }); //make an array containing the indexes of these tr elements

  console.log(indexes);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Get Selected Indexes</button>
<table>
    <tr>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
    </tr>
</table>

根据 Ozan 的 Javascript 回答,我得出了这个解决方案:

 (.map js/$ (-> (js/$ "#table tr")
            (.has ":checkbox:checked")) (fn [tr] (.index (js/$ tr))))

Ozan 的解决方案符合我的预期,但是,如果我搜索特定术语并 select 在新呈现的 table 中的一行(过滤后),我得到的索引是相对于这个新 table。为避免这种情况,我先清除过滤,然后使用 Ozan 的答案。我不认为这是最好的方法,但我把它放在这里以防它帮助任何面临同样问题的人。

我使用这行代码在获取索引之前清除过滤器。

table.search("").draw();