2013-08-31 23 views
0

它也發生在PHP中。每當pass1進入提示彈出窗口時,其下面的警報就像往常一樣顯示。但在此之後,其他警報框也顯示出來了。如何停止在pass1上執行的其他警告框?JavaScript - 爲什麼其他警報在if中執行

function download() 
{ 
x=prompt("Enter the download code here.") 
if (x=="pass1") 
{ 
alert("This function has been deleted by the administrator. Jeff, get the hell out  of here.") 
} 
if (x=="pass2") 
{ 
alert("I like pie too.") 
} 
else 
{ 
alert("The code you specified was invalid.") 
} 
} 
+0

你真的應該縮進代碼。現在很難閱讀。 –

+0

這就是爲什麼如果實施 – SarathSprakash

回答

5

變化

if (x=="pass2") 

else if (x=="pass2") 

if/elseif/else documentation

+0

謝謝。我簡直不敢相信。我曾遇到它,但我不知道它是什麼。 –

2

嘗試用else if

if (x=="pass1") 
{ 
    alert("This function has been deleted by the administrator. Jeff, get the hell out  of here.") 
} 
else if (x=="pass2") // Here use else if 
{ 
    alert("I like pie too.") 
} 
else 
{ 
    alert("The code you specified was invalid.") 
} 

您還可以使用switch

switch(x) { 
    case "pass1" : 
        alert('This function has been deleted by the administrator. Jeff, get the hell out  of here.'); 
        break; 
    case "pass2" : 
        alert('I like pie too.'); 
        break; 
    default : 
      alert('The code you specified was invalid.'); 
} 
0

您需要使用else if

function download() 
{ 
x=prompt("Enter the download code here.") 
if (x=="pass1") 
{ 
alert("This function has been deleted by the administrator. Jeff, get the hell out  of here.") 
} 
else if (x=="pass2") 
{ 
alert("I like pie too.") 
} 
else 
{ 
alert("The code you specified was invalid.") 
} 
} 
0

兩件事情,如果通過

if塊執行。當他們失敗時,他們試圖找到任何關聯的else塊並執行。在此之後,if上下文丟失。

您的代碼基本上說:

如果x == 'PASS1' - >顯示滾開這裏。 其他塊不存在。

如果x =='pass2' - >告訴他你也喜歡派。 (:/) 否則 - >顯示msg代碼無效。

所以,基本上當有人用pass1運行代碼時,他們會被告知迷路。那麼,對pass2執行另一次檢查,並且由於失敗,它們將顯示無效的代碼錯誤。

解決方案,使用else if報表指出在其他的解決方案,甚至更好use switch case.

1

因爲你的病情if (x=="pass1")滿意因此它會提示「PASS1」,

然後當你已經使用彼此的if語句是if (x=="pass2")也得到滿意,因爲這是不同於你的上述條件。

所以它更好地使用ifelse if爲您的條件。

您的代碼應該是這樣的,

if (x=="pass1") 
{ 
    alert("This function has been deleted by the administrator. Jeff, get the hell out  of here.") 
} 
else if (x=="pass2") // use of else if 
{ 
    alert("I like pie too.") 
} 
else 
{ 
    alert("The code you specified was invalid.") 
} 
1

因爲你已經使用了兩個if聲明,但您的解決方案,它需要是單if聲明。

因此,只需將您的第二個if聲明替換爲else if即可。

e.g,

if (x=="pass1") 
{ 
    alert("This function has been deleted by the administrator. Jeff, get the hell out  of here.") 
} 
else if (x=="pass2") // else if 
{ 
    alert("I like pie too.") 
} 
else 
{ 
    alert("The code you specified was invalid.") 
} 
相關問題