2012-07-02 115 views
2

假设我有这个网址:简单的JavaScript IF语句 - 什么是正确的语法?

www.example.com/product-p/xxx.htm 

以下JavaScript代码从URL中挑选出短语product-p

urlPath = window.location.pathname; 
urlPathArray = urlPath.split('/'); 
urlPath1 = urlPathArray[urlPathArray.length - 2]; 

我就可以使用文件撰写显示短语product-p

document.write(''+urlPath1+'') 

我的问题是...

如何创建一个IF语句,如果urlPath1 ='product-p',那么document.write(something),else document.write(blank)?

我试图做到这一点,但我的语法可能是错误的(我不太擅长JS)。

我最初以为的代码会是这样:

<script type="text/javascript"> 
urlPath=window.location.pathname; 
urlPathArray = urlPath.split('/'); 
urlPath1 = urlPathArray[urlPathArray.length - 2]; 

if (urlPath1 = "product-p"){ 
    document.write('test'); 
} 
else { 
    document.write(''); 
} 
</script> 

回答

5
if (urlPath1 = "product-p") 
//          ^single = is assignment 

应该是:

if (urlPath1 == "product-p") 
//   ^double == is comparison 

需要注意的是:

document.write(''+urlPath1+'') 

应该是简单的:

document.write(urlPath1) 

你concating的urlpath字符串以两个空字符串...它没有做太多。

+0

Doh!非常感谢这一点 - 在这张纸上,我认为是时候闭嘴了! – ghilton

+0

@ user1438551。不要担心这样的事情。如果你用jsLint测试了你的代码,它会告诉你这个错误。晚安战士。 – gdoron

+0

感谢您的提示gdoron,我将来肯定会使用jsLint。我也会按照描述简化(''。+ urlPath1 +'')。保重! – ghilton