亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取復選框=已選中的表的列值

獲取復選框=已選中的表的列值

侃侃無極 2024-01-03 14:13:00
我有一個表,每行都有復選框。在選擇該行的地方,我想獲取該行的列值。<table id="tblBrowse">    <thead>        <tr role="row">            <th>                <input type="checkbox" id="chkboxBrowseSelectAll" value="">            </th>            <th>Order No</th>            <th>Ship To</th>            <th>Sold To</th>        </tr>    </thead>    <tbody>        <tr role="row" class="odd">            <td>                <input type="checkbox">            </td>            <td class="sorting_1">1959-01</td>            <td>123</td>            <td>456</td>        </tr>        <!-- And lots more of the same thing -->    </tbody></table>我可以獲取選中的復選框,但如何獲取值 123 和 456?$('#btnTest').click(function () {    var checkedBoxes = document.querySelectorAll('input[type="checkbox"]:checked');    // Where do I go from here?});我可以使用 jQuery 或純 JS,但必須與 IE 兼容。
查看完整描述

2 回答

?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

您可以循環遍歷所有checkedBoxes使用.forEach()方法,然后使用.closest("tr")查找最接近該復選框的表行,然后獲取該行的列值。


var checkedBoxes = document.querySelectorAll('input[type="checkbox"]:checked');

checkedBoxes.forEach(chk => {

  chk.closest("tr").querySelectorAll('td:not(:first-child)').forEach((td, index) => {

    console.log(index, td.innerHTML)

  });

})

:not(:first-child)這里需要注意的一個重要事項是in的使用.querySelectorAll('td:not(:first-child)')。這樣做是為了我們可以忽略每行中的第一列,因為這是一個復選框列,我們的邏輯不需要它的內容。


演示:

document.getElementById("btnTest").addEventListener("click", function() {

  var checkedBoxes = document.querySelectorAll('input[type="checkbox"]:checked');

  checkedBoxes.forEach(chk => {

    chk.closest("tr").querySelectorAll('td:not(:first-child)').forEach((td, index) => {

      console.log(index, td.innerHTML)

    });

  })

});

<button id="btnTest">Get Value</button>

<table id="tblBrowse">

  <thead>

    <tr role="row">

      <th>

        <input type="checkbox" id="chkboxBrowseSelectAll" value="">

      </th>

      <th>Order No</th>

      <th>Ship To</th>

      <th>Sold To</th>

    </tr>

  </thead>

  <tbody>

    <tr role="row" class="odd">

      <td>

        <input type="checkbox">

      </td>

      <td class="sorting_1">1959-01</td>

      <td>123</td>

      <td>456</td>

    </tr>

    <!-- And lots more of the same thing -->

  </tbody>

</table>


查看完整回答
反對 回復 2024-01-03
?
浮云間

TA貢獻1829條經驗 獲得超4個贊

您可以為每個復選框賦予一個值并將其值存儲在變量中

var xyz=checkedBoxes.value;

xyz 將是一個數組


查看完整回答
反對 回復 2024-01-03
  • 2 回答
  • 0 關注
  • 178 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號