2

次の URL があるとします。

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

次の JavaScript コードはproduct-p、URL からフレーズを選択します。

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

次に、document.write を使用して次のフレーズを表示できますproduct-p

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

私の質問は...

if urlPath1 = 'product-p' then document.write (something), else document.write (blank) のような IF ステートメントを作成するにはどうすればよいですか?

私はこれをやろうとしましたが、私の構文はおそらく間違っています (私は 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>
4

1 に答える 1

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

    次のようにする必要があります。

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

ご了承ください:

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

単純にする必要があります:

document.write(urlPath1)

文字列を2つの空の文字列と連結してurlpathいます...あまり効果がありません。

于 2012-07-02T22:57:12.967 に答える