单击 $this 复选框

On Click of $this check checkbox

我正在设置一个过滤系统,它将根据所选过滤器过滤搜索结果。 objective 是让整个容器都可以点击,而不仅仅是一个标签。

//html

<div class="Container">
<input type="checkbox" class="inputBx" data-type="prodType">
<div class="lbl">1</div>
</div>
<div class="Container">
<input type="checkbox" class="inputBx" data-type="prodType">
<div class="lbl">2</div>
</div>
<div class="Container">
<input type="checkbox" class="inputBx" data-type="prodType">
<div class="lbl">3</div>
</div>

//jquery(我已经包含了几个我尝试过的不同选项)。最终,当用户单击其中一个容器时,我希望检查该特定容器内的输入。

 $('.Container').on('click', function(){
    
            $(this).closest('div').find('input').click();
        $(this).find('input').click();
        $(this).find('input[data-type="prodType"]').click();
    
    });

提前感谢您的帮助!

试试这个:

$('.Container').on('click', function(){ 
            $(this).closest('div').find('input').prop('checked', true);
        $(this).find('input').prop('checked', true);
        $(this).find('input[data-type="prodType"]').prop('checked', true);
    
    });

问题是在输入上引发多个点击事件的组合,这些点击事件通过切换 input on/off 相互抵消,以及多次捕获事件的事件传播,并且输入再次切换多次。

要解决此问题,您可以确保触发事件的元素 而不是 input,并适当切换 checked 状态。注意这里使用 closest() 来获取 .Container 元素,因为事件可以在子 .lbl 元素或 .Container 本身上触发。

$('.Container').on('click', e => {
  let $target = $(e.target);
  if ($target.is('input'))
    return;

  $target.closest('.Container').find('input').prop('checked', (i, c) => !c);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="Container">
  <input type="checkbox" class="inputBx" data-type="prodType">
  <div class="lbl">1</div>
</div>
<div class="Container">
  <input type="checkbox" class="inputBx" data-type="prodType">
  <div class="lbl">2</div>
</div>
<div class="Container">
  <input type="checkbox" class="inputBx" data-type="prodType">
  <div class="lbl">3</div>
</div>

话虽如此,这种方法并不理想。您可以通过使用根本没有 JS 的普通 HTML 来轻松实现它 - 使用 label 元素。如果您尝试以上述方式实现目标的原因是出于样式原因,那么可以使用 CSS 轻松地为 label 元素设置样式以满足您的需要。试试这个:

label { display: block; }
<label class="Container">
  <input type="checkbox" class="inputBx" data-type="prodType">
  <span class="lbl">1</span>
</label>
<label class="Container">
  <input type="checkbox" class="inputBx" data-type="prodType">
  <span class="lbl">2</span>
</label>
<label class="Container">
  <input type="checkbox" class="inputBx" data-type="prodType">
  <span class="lbl">3</span>
</label>