Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable in an if / else statement

Tags:

jquery

I am creating a variable that is equal to the text of a <a> that has been clicked on, and then use the variable in an if / else statement but cant get it to work. I know the variable is right, and I know the function works because I can replace it with a "whatever.html" and it work. However I cant get the variable to work in its place:

   $(".themenu a").click(function(){
          var stuff = $(this);
          if (stuff == "Home"){
                 $.get("main.html", function(data){
                 $(".content").append(data);
          }, "html");
   }
like image 513
fridgerator Avatar asked Apr 27 '26 10:04

fridgerator


2 Answers

$(this); will get you a jQuery object, not the text of it, so that won't be equal to "Home". Use

var stuff = $(this).text();

or

var stuff = $(this).html();
like image 76
Nanne Avatar answered May 04 '26 19:05

Nanne


You are setting your stuff variable to reference the jQuery object returned by $(this), when what you really want is the text of the element in that jQuery object like so:

var stuff = $(this).text();

EDIT: note that in your click handler this will be equal to the <a> element you could also do this:

var stuff = this.innerHTML;
like image 38
nnnnnn Avatar answered May 04 '26 21:05

nnnnnn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!