0

I'm checking a number of 'read more' links on my blog, and either hiding the link (for the first two posts), or hiding the content and keeping the link. I'm running the links' id attributes through an if ... else statement that looks like so:

$(document).find('.contentclicker').each(function(){
    var pt = $(this).parent().attr('id');
    if (pt == "postnum1" ||  "postnum2"){
        $(this).hide();
    }
    else{
        $(this).next().hide();
    }

    });

Note: There's some jQuery in there, but it's not relevant. I know from debugging that the var pt is being set correctly to post_num_1, post_num_2, etc. - but when it evaluates post_num_3 and so on, it doesn't go to the else. I've tried == and ===, among other things, and I can't figure out what's wrong.

Any suggestions?

4 Answers 4

12

I am pretty sure you cannot do if (pt == "postnum1" || "postnum2") in javascript. Try if (pt == "postnum1" || pt == "postnum2"). Basically, even if the first conditional of pt == "postnum1" were false, it'd treat the second conditional as true which would avoid the else clause at the bottom. At least, that's what I think.

Sorry if I misunderstood your question.

Sign up to request clarification or add additional context in comments.

1 Comment

That did it. Thanks for the rapid reply!
3

JavaScript is not strictly typed, it means in particular that it gives you some leeway int your data types and always tries to coerce the expression value to the data type it thinks to be your intention.

In your if statement it tries co convert the part after || to boolean and result of conversion of "postnum2" is always true.

I think what you intended was (pt == "postnum1" || pt == "postnum2")

Comments

2

The second part of condition "postnum2" always evaluates to true. You have to convert condition to first answer. Also your post says post_num_1, post_num_2, etc, but you are checking for post_num1.

Comments

2

Instead of if (pt == "postnum1" || "postnum2")

try

if ((pt == "postnum1" ) || (pt == "postnum2"))
{
  // something
}

Also you can do something in the switch case(as an alternative)

switch(pt)
{
 case "postnum1":
 case "postnum2" : $(this).hide(); break;
 default: $(this).next().hide(); break;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.