首页 > 解决方案 > 将使用 jquery 选中的复选框仅设置为子元素

问题描述

如何仅将复选框设置为使用 jquery 选中的子元素?我有以下html代码

<div id="mon">
  <span>Tue</span>
  <input type="text" class="start" name="mon_start" placeholder="Start" value="">
  <input type="text" class="end" name="mon_end" placeholder="End" value="">
  <label><input type="checkbox" class="h24" value="1">24hrs</label>
</div>
<div id="tue">
  <span>Tue</span>
  <input type="text" class="start" name="tue_start" placeholder="Start" value="">
  <input type="text" class="end" name="tue_end" placeholder="End" value="">
  <label><input type="checkbox" class="h24" value="1">24hrs</label>
</div>

我尝试了以下代码,但它总是更改 div #mon 的复选框:

$('#mon, #tue input').on('change', function(){
  if ($(this).find('.start').val() == '00:00' && $(this).find('.end').val() == '24:00'){
      $(this).find('.h24').prop('checked', true);
  } else {
      $(this).find('.h24').prop('checked', false);
  }
});

标签: jquery

解决方案


选择器#mon, #tue input选择#monDIV 和里面的所有输入#tue。但是$(this).find()当是输入时将不起作用this,因为它们不是容器。

您应该只使用$("#mon, #tue"). The更改event will bubble up from all the inputs in the DIV, and then you can select other elements within the DIV using$(this)`


推荐阅读