简单的javascript IF语句-正确的语法是什么?
假设我有这个URL:简单的javascript IF语句-正确的语法是什么?,javascript,syntax,if-statement,statements,Javascript,Syntax,If Statement,Statements,假设我有这个URL: www.example.com/product-p/xxx.htm 以下javascript代码从URL中选择短语product-p: urlPath = window.location.pathname; urlPathArray = urlPath.split('/'); urlPath1 = urlPathArray[urlPathArray.length - 2]; 然后,我可以使用document.write显示短语product-p: document.
www.example.com/product-p/xxx.htm
以下javascript代码从URL中选择短语product-p
:
urlPath = window.location.pathname;
urlPathArray = urlPath.split('/');
urlPath1 = urlPathArray[urlPathArray.length - 2];
然后,我可以使用document.write显示短语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>
urlPath=window.location.pathname;
urlPathArray=urlPath.split('/');
urlPath1=urlPathArray[urlPathArray.length-2];
如果(urlPath1=“产品-p”){
文件。编写(“测试”);
}
否则{
文件。写(“”);
}
应该是:
if (urlPath1 == "product-p")
// ^ double == is comparison
请注意:
document.write(''+urlPath1+'')
应该简单地说:
document.write(urlPath1)
您正在将
urlpath
字符串与两个空字符串关联。。。没什么用。Doh!非常感谢你的提醒,我想是时候休息一下了@用户1438551。别担心那样的事情会发生。如果您使用jsLint测试代码,它会告诉您这个错误。晚安,勇士。谢谢你给我的提示,我以后一定会使用jsLint。我还将简化('.+urlPath1+'')如前所述。当心!
document.write(urlPath1)