ghi*_*ton 2 javascript syntax if-statement statements
假设我有这个URL:
www.example.com/product-p/xxx.htm
Run Code Online (Sandbox Code Playgroud)
以下javascript代码product-p从URL中挑选出该短语:
urlPath = window.location.pathname;
urlPathArray = urlPath.split('/');
urlPath1 = urlPathArray[urlPathArray.length - 2];
Run Code Online (Sandbox Code Playgroud)
然后我可以使用document.write来显示短语product-p:
document.write(''+urlPath1+'')
Run Code Online (Sandbox Code Playgroud)
我的问题是......
如何创建一个IF语句,如果urlPath1 ='product-p'然后是document.write(某事物),否则是document.write(空白)?
我试过这样做,但我的语法可能是错的(我不太擅长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>
Run Code Online (Sandbox Code Playgroud)
if (urlPath1 = "product-p")
// ^ single = is assignment
Run Code Online (Sandbox Code Playgroud)
应该:
if (urlPath1 == "product-p")
// ^ double == is comparison
Run Code Online (Sandbox Code Playgroud)
注意:
document.write(''+urlPath1+'')
Run Code Online (Sandbox Code Playgroud)
应该简单地说:
document.write(urlPath1)
Run Code Online (Sandbox Code Playgroud)
你urlpath用两个空字符串来串联字符串......它没有做太多.