Javascript - if statement not working?

2020-04-18 07:05发布

I'm trying to set a class to active depending on the url. I'm trying to use the code below, but in every case, it activates the active class for the second tab.

var pathname = window.location.pathname;

if(pathname = '/learn/subsection2') {
            $("ul.tabs li:eq(1)").addClass("active").show(); //Activate second tab
            $(".tab_content:eq(1)").show(); //Show second tab content
    } else {
            $("ul.tabs li:first").addClass("active").show(); //Activate first tab
            $(".tab_content:first").show(); //Show first tab content
    }

5条回答
狗以群分
2楼-- · 2020-04-18 07:46

You used a = instead of a == or === in your comparison. This is why many programmers shift the statement around so it throws an error vs. running code unintentionally... its a very common mistake!

Here is an example of the same ifg statement switched around. Had you used this format, but made the same mistake, it would have thrown an error which would have helped you located it faster:

if('/learn/subsection2' == pathname){ ... }
查看更多
Rolldiameter
3楼-- · 2020-04-18 07:53

You are assigning rather than checking for equality in your if statement.

if(pathname == '/learn/subsection2') {
...
查看更多
太酷不给撩
4楼-- · 2020-04-18 07:53
if(pathname = '/learn/subsection2') { // assignment
if(pathname == '/learn/subsection2') { // test for equality
if(pathname === '/learn/subsection2') { // test for equality without type coercion
查看更多
走好不送
5楼-- · 2020-04-18 07:56

You're using = instead of ==, a common programming error. = is assignment, == is comparison.

if (pathname == '/lean/subsection2') { // ...

When using =, it assigns the string /lean/subsection2 to the variable pathname and evaluates it as a boolean value, which is always true (it'd have to be false or undefined), so it always takes the positive condition block.

查看更多
Explosion°爆炸
6楼-- · 2020-04-18 08:04

Use == instead of = in the if statement.

查看更多
登录 后发表回答