jQuery,使用委派事件时一次点击



我有一个问题,我无法解决自己,我知道你们可以帮助我。

我有一个div包含动态生成的内容,确切地说,它会生成内部内容的正方形,每个正方形都有一个交叉图标,因此它可以消失并做其他事情,事实是,正方形需要时间才能褪色外出,可以单击一次以上,这引起了我的问题,因为它减少了计数器,我声明的次数超过了,并且与其他代码相交:(

这是我的代码:

$("#yha-tools").on("click", ".close", function (){
    $(this).fadeOut(500);
    cnr--;
});

我尝试使用$("#yha-tools").one,但这并不能帮助我实现目标。

我不确定您拥有多少按钮,但是在这种情况下,您肯定可以使用.data()。您可以检查该元素是否尚未单击并使用所需的操作进行处理。

$("#yha-tools").on("click", ".close", function (){
 
    var clicked = $(this).data('clicked'); // This will `undefined` in the first run.
    
    if( ! clicked || clicked != true ){ // If element has not been clicked 
        $(this).fadeOut(500);
        
        $(this).data('clicked', true); 
        
        // do whatever else you want here.
    
    } 
    
    console.log( clicked );
    
});
$('[data-action="addBtn"]').on('click', function(){
    $("#yha-tools").append('<button class="close">Close me!</button>');
});
$('[data-action="showBtns"]').on('click', function(){
    $('.close').show();
});
#yha-tools {
   padding: 10px;
   margin:10px;
   border:2px solid #ddd;
}
.close {
   margin: 0px 0px 10px 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="yha-tools"></div>
<button data-action="addBtn">Add button</button>
<button data-action="showBtns">Show all buttons</button>

fadeOut()之前添加此语句:

$(this)[0].style.pointerEvents = "none"

demo

var cnr = 6;
$("#yha-tools").on("click", ".close", function() {
  $(this)[0].style.pointerEvents = 'none';
  $(this).fadeOut(500);
  cnr--;
  $('output').text(cnr);
});
.close {
  width: 20px;
  height: 15px;
  font-size: 20px;
  padding-bottom: 5px;
  text-align: center;
  border: 1px solid grey;
  cursor: pointer;
  margin: 10px;
}
output {
  color: red;
  font-size: 32px;
  font-family: Consolas;
}
<section id='yha-tools'>
  <div class='close'>+</div>
  <div class='close'>+</div>
  <div class='close'>+</div>
  <div class='close'>+</div>
  <div class='close'>+</div>
  <div class='close'>+</div>
</section>
<output>6</output>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

最新更新