无论首先单击哪个复选框,都需要调用函数1次-.one()的一些变体

Need to call function 1 time no matter which checkbox is clicked first - some variation of .one()

本文关键字:one 1次 函数 调用 单击 复选框      更新时间:2023-09-26

我有一个页面,上面有很多产品,所有产品都是同一类型的。我为产品建立了一个带有复选框的过滤功能。加载页面时,将加载所有产品,默认情况下复选框将取消选中。

目标:当用户第一次点击复选框来过滤产品时,无论点击哪个复选框,我都希望特定功能只运行一次,在这种情况下,隐藏所有产品。当我使用.one()时,它为每个复选框工作一次,这不是我想要的结果。我需要它运行一次,周期。无论单击哪个复选框。

下面是HTML和jQuery,非常感谢您的帮助,并感谢您抽出时间。

HTML:

<div class="col-md-3 test-one"><label><input id="fourth-cbox" type="checkbox" value="fourth_checkbox" />FOURTH COLLECTION</label></div>
<div class="col-md-3 test-one"><label><input id="first-cbox" type="checkbox" value="first_checkbox" />FIRST COLLECTION</label></div>
<div class="col-md-3 test-one"><label><input id="second-cbox" type="checkbox" value="second_checkbox" />SECOND COLLECTION</label></div>
<div class="col-md-3 test-one"><label><input id="third-cbox" type="checkbox" value="third_checkbox" />THIRD COLLECTION</label></div>

jQuery:

 $(document).ready(function() {
  $(".test-one").one('click',function(){ 
    $('div[data-product]').parents("li").hide();
  });
});

您可能需要使用JQuery 提供的.unbind()方法

$(document).ready(function() {
  $(".test-one").bind('click',function(){ 
    $('div[data-product]').parents("li").hide();
    $(".test-one").unbind('click');
  });
});

$(document).ready(function() {
    var test = true;//set to true
   $(".test-one").change(function() {
     if(test){//will run only once during var true
       alert('one')
       test =false;//set to false
       }
     
   });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3 test-one"><label><input id="fourth-cbox" type="checkbox" value="fourth_checkbox" />FOURTH COLLECTION</label></div>
<div class="col-md-3 test-one"><label><input id="first-cbox" type="checkbox" value="first_checkbox" />FIRST COLLECTION</label></div>
<div class="col-md-3 test-one"><label><input id="second-cbox" type="checkbox" value="second_checkbox" />SECOND COLLECTION</label></div>
<div class="col-md-3 test-one"><label><input id="third-cbox" type="checkbox" value="third_checkbox" />THIRD COLLECTION</label></div>

喜欢这个吗

  1. 将变量设置为true
  2. 检查变量if true运行函数,然后将其设置为false
  3. 函数将不会运行,因为变量现在为false

我会做一些类似的事情

var flag = false;
$('element').on('click' , function(e){
    if(!flag){
        callYourFunction();
        flag = true;
    }
}

我会设置一个标志来表示该方法已经运行。