Javascript – if语句不起作用?

我正在尝试根据url将类设置为活动状态。 我正在尝试使用下面的代码,但在每种情况下,它都会激活第二个选项卡的活动类。

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 } 

您正在分配而不是在if语句中检查是否相等。

 if(pathname == '/learn/subsection2') { ... 
 if(pathname = '/learn/subsection2') { // assignment if(pathname == '/learn/subsection2') { // test for equality if(pathname === '/learn/subsection2') { // test for equality without type coercion 

您正在使用=而不是== ,这是一个常见的编程错误。 =是赋值, ==是比较。

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

当使用= ,它将字符串/lean/subsection2分配给变量pathname 并将其计算为布尔值,该值始终为true(它必须为false或未定义),因此它始终采用正条件块。

if语句中使用==而不是=

您在比较中使用了=而不是===== 。 这就是为什么许多程序员改变语句的原因所以它会导致错误而不是无意中运行代码……这是一个非常常见的错误!

这是一个相同的if g语句切换的例子。 如果你使用这种格式,但犯了同样的错误,它会抛出一个错误,这会帮助你更快地找到它:

 if('/learn/subsection2' == pathname){ ... }