如何从同一 <td> 标签下通过复选框值获取隐藏值

How can I get hidden value by checkbox value from under the same <td> tag

我有一个 table 这样的:

<table id="TempTable">
 <tr>
  <td>
   <input type="checkbox" id="chkbox1"/>
   <input type="hidden" value="1" />
  </td>
 </tr>
 <tr>
  <td>
   <input type="checkbox" id="chkbox2"/>
   <input type="hidden" value="2" />
  </td>
 </tr>
 <tr>
  <td>
   <input type="checkbox" id="chkbox3"/>
   <input type="hidden" value="3" />
  </td>
 </tr>
</table>

而且我想在与选中的复选框相同的 td 中获取隐藏值。

我试过这个:

$("#TempTable tr input:checkbox:checked").each(function(){
  alert($("#"+this.id).parent("td").child("input:hidden").val());
});

当然,我得到我想要的值后,我会把它保存到一个数组中。

试试这个:

$("input[type='checkbox']").each( function (){
    var value = $(this).parent().find("input:hidden").val();
    // this will return the value of each hidden field
});

不确定为什么值不在复选框上,这会简化代码。

但是对于您的代码,您只需使用 next 和 map。

$(":checkbox").on("change", function() {
    var vals = $(":checkbox:checked").map( function(){
        return $(this).next().val();
    }).get();
    console.log(vals);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="TempTable">
 <tr>
  <td>
   <input type="checkbox" id="chkbox1"/>
   <input type="hidden" value="1" />
  </td>
 </tr>
 <tr>
  <td>
   <input type="checkbox" id="chkbox2"/>
   <input type="hidden" value="2" />
  </td>
 </tr>
 <tr>
  <td>
   <input type="checkbox" id="chkbox3"/>
   <input type="hidden" value="3" />
  </td>
 </tr>
</table>

正如我在将值放在复选框之前所说的那样简化了它

$(":checkbox").on("change", function() {
    var vals = $(":checkbox:checked").map( function(){
        return this.value;
    }).get();
    console.log(vals);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="TempTable">
 <tr>
  <td>
   <input type="checkbox" id="chkbox1" value="1"/>
  </td>
 </tr>
 <tr>
  <td>
   <input type="checkbox" id="chkbox2" value="2"/>
  </td>
 </tr>
 <tr>
  <td>
   <input type="checkbox" id="chkbox3" value="3"/>
  </td>
 </tr>
</table>

您可以使用兄弟姐妹和隐藏的输入类型来获取值。

$("#TempTable tr input[type=checkbox]:checked").each(function(){
   $(this).siblings('input[type=hidden]').val()
});