【问题标题】:Finding index of table rows with checked checkbox使用选中的复选框查找表行的索引
【发布时间】:2016-12-13 11:56:25
【问题描述】:

我有一个 html 表格,其中每行的第一个单元格包含一个复选框。我想用选中的复选框获取每一行的索引。我可以以 js/$ 的身份访问 JQuery

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

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

【问题讨论】:

    标签: jquery checkbox html-table clojurescript


    【解决方案1】:

    我不熟悉问题中的语法,但是这个 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>

    【讨论】:

    • 我正在寻找使用 ClojureScript 的解决方案 :-)
    • 我只是在编辑提及它。我不熟悉closurescript 语法,但这是非常标准的jquery 代码。翻译过来应该很容易。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 1970-01-01
        • 2012-12-05
        • 2019-04-02
        • 1970-01-01
        • 1970-01-01
        • 2016-07-13
        • 2015-06-18
        • 1970-01-01
        相关资源
        最近更新 更多