Javascript 如果根据列名id选中复选框,则查找id列的值

Javascript 如果根据列名id选中复选框,则查找id列的值,javascript,jquery,html,Javascript,Jquery,Html,我必须根据列名在同一行中找到其复选框被选中的id列的值,因为id列的位置不是固定的。它可以是表中的第一个、最后一个或中间。我已应用以下代码: <table id="rowclick2" border="1"> <tr> <th>Select</th> <th>Des</th> <th>ID</th> </tr> <

我必须根据列名在同一行中找到其复选框被选中的id列的值,因为id列的位置不是固定的。它可以是表中的第一个、最后一个或中间。我已应用以下代码:

<table id="rowclick2" border="1">
    <tr>
        <th>Select</th>
        <th>Des</th>
        <th>ID</th>
    </tr>
    <tr>
        <td>
            <input type="checkbox" name="vehicle" value="Bike">
        </td>
        <td>col 2, row 1</td>
        <td>col 3, row 1</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" name="vehicle" value="Car"> </td>
        <td>col 2, row 2</td>
        <td>col 3, row 2</td>
    </tr>
</table>

请帮助查找复选框已选中的id值。我不熟悉jquery、javascript。

我建议使用以下方法:

// binding a change event-handler to <input type="checkbox" /> elements:
$('input[type=checkbox]').change(function() {
  // assuming you want this to run only when the checkbox is checked:
  if (this.checked) {
    // find the <th> elements:
    var ID = $('th').filter(function() {
        // find those <th> elements whose trimmed-text is exactly 'ID':
        return $.trim($(this).text()) === 'ID';
      // get the cellIndex property of that element (or the first matched element):
      }).prop('cellIndex'),
      // find the closest <tr> element from the checked <input />:
      IDVal = $(this).closest('tr')
      // find the descendant <td> elements:
      .find('td')
      // find the <td> with the same cellIndex as the <th>
      .eq(ID)
      // retrieve the text:
      .text();
    console.log(IDVal);
  }
});

挑选
Des
身份证件
第2列,第1行
第3栏,第1行
第2列,第2排
第3栏,第2行

我希望这能有所帮助。请看演示

根据我对此的理解,请帮助查找其复选框已选中的id

$(document).ready(function(){
    $(":checkbox").click(function(){
        alert( $(this).val() );
    });
});

将id添加到复选框
id=“first”
id=“second”
以获取元素:

    <tr>
    <td><input type="checkbox" name="vehicle" value="Bike" id="first"></td>
    <td>col 2, row 1</td>
    <td>col 3, row 1</td>
</tr>`enter code here`
<tr>
    <td><input type="checkbox" name="vehicle" value="Car" id="second"> </td>
    <td>col 2, row 2</td>
    <td>col 3, row 2</td>
</tr>

你现在犯了什么错误?另外,您可以切换列位置,这就是为什么ID列从不在同一位置的原因吗?将“bhh”和“cbjhj”的警报更改为警报($(this).val());,如果选中复选框,警报将显示值,这是您想要的吗?那么您如何知道该列是ID列。它是否总是具有相同的标题
ID
    <tr>
    <td><input type="checkbox" name="vehicle" value="Bike" id="first"></td>
    <td>col 2, row 1</td>
    <td>col 3, row 1</td>
</tr>`enter code here`
<tr>
    <td><input type="checkbox" name="vehicle" value="Car" id="second"> </td>
    <td>col 2, row 2</td>
    <td>col 3, row 2</td>
</tr>
if(document.getElementById("first").checked == true){
  console.log("do something here 1");
}
if(document.getElementById("second").checked == true){
  console.log("do something here 2");
}