JQuery executing both branches of an if-else statement in Rails

I have the following jQuery page on a Rails page:

$(document).on('click','.reportsArrow', function() {
    if ( $(this).parent().hasClass('reportCollapsed') ) {
      console.log("A");
      $(this).parent().removeClass('reportCollapsed');
    }else{
      $(this).parent().addClass('reportCollapsed');
        console.log("B");
    }
});

When I click an item with reportsArrowand without reportCollapsed, the log shows

B

A

It is assumed that he performs the part else, and then performs the part if. I want the function to be executed only once per click and to follow only one code. Why is this done twice and how to stop it? I should note that this works correctly in layouts created by a web designer (HTML / CSS / JS only). It seems the problem is with Rails.

EDIT:

We found a working solution:

$('.reportsArrow').click(function() {
    $(this).parent().toggleClass('reportCollapsed');
}); 
+4
source share
7 answers

, , javascript , .

, , . , ( ), : " ". .

, catch , : ( ), .

, :

$(document).on('click','.reportsArrow', function() {
    //...
});

:

$('.reportsArrow').click(function () {
    //..
});

API jQuery .on(), , , , .one() , "# 1" . , .

+3

DOM. event.stopPropagation(). toggleClass .

$(document).on('click','.commonClass', function(event) {
   event.stopPropagation();
   $(this).parent().toggleClass('newClass');
});
+6

. , toggleClass:

$(document).on('click','.commonClass', function(e) {
  e.stopPropagation();
  $(this).parent().toggleClass('newClass') 
});
+2

,

, DOM. , . , event.stopPropagation()

$(document).on('click','.commonClass', function(event) {
      event.stopPropagation();
      $(this).parent().toggleClass('newClass');

});
+2

. Firefox HTML-.

, :

function onClick(ev) {
  console.log(ev.currentTarget, '\n', ev.target, '\n', ev);
  if(ev.target === ev.currentTarget)
    console.log($(this).parent().toggleClass('newClass').hasClass('newClass') ? 'B' : 'A');
};

EDIT: , :

$(document).on('click', '.commonClass', onClick);
+1

jQuery, :not,

$(document).on('click','.reportCollapsed > .reportsArrow', function() {
  $(this).parent().removeClass('reportCollapsed')
  console.log("A");
})

$(document).on('click','not:(.reportCollapsed) > .reportsArrow', function() {
  $(this).parent().addClass('reportCollapsed')
  console.log("B");
})
+1

Given that this works once (press> else> B), can it happen that something listens for DOMSubtreeModified or other DOMChange events that trigger a click on the document again?

Have you tried debugging / after calls after pressing urgently? Afaik chrome has a nice gui to do this.

+1
source

Source: https://habr.com/ru/post/1545163/


All Articles