Problem with '.data()' and its value within an if

Asked

Viewed 43 times

2

I’m creating some If's not to lose the habit of using them, but when trying something a little different from what I usually do, an error occurs, the if does not work. How can I fix ? I tried in the following ways:

if($('.carousel-indicators li.active').data('slide-to').val() = 0){
    console.log('Teste');
};
ERRO : Uncaught ReferenceError: Invalid left-hand side in assignment

and

if($('.carousel-indicators li.active').data('slide-to') = 0){
    console.log('Teste');
};
ERRO : Uncaught TypeError: $(...).data(...).val is not a function
  • A sign of equals was missing .val() == 0 and why are you using .data().val()??

  • Because simply the . data() had not worked

2 answers

3

When you compare something you need to use == or === (Strict comparison).
The = is to assign value to some variable.

  • 1

    Why the -1? The answer is right and explains the AP problem...

  • I also think the problem proves from there, I didn’t realize the least -1, unless I missed something @Sergio

  • @Miguel someone gave -1 and another person +1 to compensate, probably Sergio

  • @Miguel I also did not, so (and because the answer is right) I gave +1

  • Yap also think

3


Two problems:

  • the .data() already gives you a String, you do not need (nor should you) use .val()

  • comparison should be made with == or ===, use only = is an assignment.

Solution:

if($('.carousel-indicators li.active').data('slide-to') == 0){
    console.log('Teste');
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.