2009-11-19 74 views
1

我想設置一個類來激活取決於網址。我試圖使用下面的代碼,但是在任何情況下,它都會激活第二個選項卡的活動類。Javascript - 如果陳述不起作用?

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 
    } 

回答

6

您正在分配而不是在if語句中檢查相等性。

if(pathname == '/learn/subsection2') { 
... 
+3

呃犯罪......這是漫長而漫長的一天... :)謝謝。 :::咧嘴笑,然後隱藏在一塊岩石下::: – phpN00b 2009-11-19 00:56:37

+0

是的,你正在分配,而不是比較路徑名和字符串的值。 – putolaruan 2009-11-19 00:56:38

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

只適用於PHP – mauris 2009-11-19 00:59:14

+3

和JavaScript,Ruby和C#... – 2009-11-19 01:00:06

+2

和javascript。 – 2009-11-19 01:00:57

4

您使用=代替==,一種常見的編程錯誤。 =是轉讓,==是比較。

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

當使用=,它的字符串/lean/subsection2賦予變量pathname評估它作爲一個布爾值,它始終是真(它不得不是虛假的或未定義的),所以它總是採取積極的條件。

4

if聲明中使用==而不是=

2

您在比較中使用了=而不是=====。這就是爲什麼很多程序員會將聲明轉移到所以它會無意中拋出一個錯誤與運行代碼的錯誤......它是一個非常常見的錯誤!

下面是同樣的if g語句切換的例子。如果你使用這種格式,但犯了同樣的錯誤,它會拋出一個錯誤,它會幫助你更快地找到它:

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