Jquery, On one click when using delegated events

时间:2017-12-18 07:23:33

标签: javascript jquery

I have a question I haven't been able to solve myself, I know you guys can help me.

I have a div that contains dynamically generated content, to be precise it generates squares with content inside, each square has a cross icon so it can disappear and do some other stuff, the thing is that the square takes its time to fade out and it can be clicked more than once and it's causing me problems because it decreases a counter I declared more times than it should and messes up with other code :(

Here is my code:

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

I tried to use $("#yha-tools").one but it doesn't help me meet my goal.

2 个答案:

答案 0 :(得分:1)

I am not sure how many buttons you have, but you can certainly make use of In [17]: A Out[17]: [[1, 1, 1], [2, 2, 2], [3, 3, 3]] In [18]: x Out[18]: [[1], [2], [3]] In [19]: matrix_mult(A, x) Out[19]: [[6], [12], [18]] in this case. You can check if the element has not been clicked yet and processed with desired action.

.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;
}

答案 1 :(得分:0)

Add this statement before the df1.foreach(lookup):

fadeOut()

Demo

$(this)[0].style.pointerEvents = "none"
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;
}