0

In my function, I adding a class to current object. But when run again, the hasClass function doesn't detect the class I added.

So I can show a example that;

   var object = {
       func : function() {
           if ( $(this).hasClass('myclass') )
               // ...
           else
               $(this).addClass('myclass');
       }
   }

   $('#myobj').on('click', object.func);

Now, I getting JSON data with AJAX. After I parsing JSON data and creating a DOM elements with this. When I click this dom elements, this function triggering successfully. Even addClass function works successfully. But when the function is triggered again, the hasClass function does not read the newly added class.

Thanks.

K. Yılmaz
  • 21
  • 4
  • 1
    Please add a [mcve] that shows the problem (because this should work: https://jsfiddle.net/kq6pwzvo/) – Andreas Sep 02 '20 at 08:30
  • 1
    What element is `$(this)`? When and where `myFunction()` is being called? With just what you provided is impossible to see what might be wrong. – emerson.marini Sep 02 '20 at 08:33
  • I updated. I hopefully you can understand. – K. Yılmaz Sep 02 '20 at 08:39
  • Your function is being executed even before you click on the element. This might solve your problem: `$('#myobj').on('click', object.func);` – emerson.marini Sep 02 '20 at 08:39
  • https://stackoverflow.com/questions/19503943/javascript-function-is-being-called-on-page-load – emerson.marini Sep 02 '20 at 08:40
  • I'm sorry, already using same. Just I made a mistake when type here. – K. Yılmaz Sep 02 '20 at 08:42
  • We will need to see more of your code then. Can't you put together a Codepen or JSFiddle to show us? – emerson.marini Sep 02 '20 at 08:51
  • Duplicate of: [How to access the correct `this` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) -> ["Common problem: Using object methods as callbacks/event handlers"](https://stackoverflow.com/a/20279485/402037) – Andreas Sep 02 '20 at 08:57
  • I solved this problem! It appeared because DOM elements were included in the page later. – K. Yılmaz Sep 02 '20 at 09:01

0 Answers0