如何在所有元素上只触发一次toggle()?

时间:2017-04-26 07:08:15

标签: javascript jquery function click toggle

我怎样才能触发一次切换?

我有......

<%= f.check_box :push %>
<label for="challenge_push" class="reminder-choices">Push</label>
<%= f.check_box :message %>
<label for="challenge_message" class="reminder-choices">Text</label>
<%= f.check_box :mail %>
<label for="challenge_mail" class="reminder-choices">Email</label>

<script>
  $('.reminder-choices').click(function(){
    $(".hide-remind").toggle();
  });
</script>

我试过......

# Same behavior as above. Still toggles back and forth.
$('.reminder-choices').one("click", function(){
    $(".hide-remind").toggle();
});

换句话说,单击.reminder-choices一次后,切换将起作用,否则如果再次单击它则无效。

2 个答案:

答案 0 :(得分:3)

你的第二次尝试应该有效。你也可以这样做。

&#13;
&#13;
$('.reminder-choices').on('click.reminder', function() {

    $(".hide-remind").toggle();
    $(this).off('click.reminder');
    
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="reminder-choices">Click Here</div>
<div class="hide-remind">Will be toggled</div>
&#13;
&#13;
&#13;

修改:如果您有多个元素,并希望在点击其中一个元素后忽略所有元素的点击次数:

&#13;
&#13;
$('.reminder-choices').on('click.reminder', function() {

    $(".hide-remind").toggle();
    $('.reminder-choices').off('click.reminder');
    
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="reminder-choices">Click Here</div>
<div class="reminder-choices">Or Here</div>
<div class="reminder-choices">Or Here</div>

<div class="hide-remind">Will be toggled</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

将代码包装在容器中,然后委派事件。

&#13;
&#13;
$('.container').one('click', '.reminder-choices', function() {
  $(".hide-remind").toggle();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="reminder-choices">Click Here</div>
  <div class="reminder-choices">Or Here</div>
  <div class="reminder-choices">Or Here</div>
</div>
<div class="hide-remind">Will be toggled</div>
&#13;
&#13;
&#13;