该部分是foo.com/agriculture。它有一个与javascript中的名称对应的横幅图像。我需要内部页面foo.com/agriculture/harvest有一个单独的横幅而不是foo.com/agriculture。我正在为每个页面进行横幅交换的脚本如下:
<script type="text/javascript">
var dir = location.pathname.split("/")[1];
//var dir2 = location.pathname;
if (dir == "agriculture")
document.write('<IMG SRC="/images/ib_agriculture.jpg" WIDTH=1024 HEIGHT=91 BORDER=0>')
else if (dir == "showcase")
document.write('<IMG SRC="/images/ib_show.jpg" WIDTH=1024 HEIGHT=91 BORDER=0>')
else if (dir == "contact")
document.write('<IMG SRC="/images/ib_contact.jpg" WIDTH=1024 HEIGHT=91 BORDER=0>')
else if (dir == "distribution")
</script>
我尝试了以下不同的代码,尝试将内部页面foo.com/agriculture/harvest指定为单独的横幅。
var dir = location.pathname.split("/")[1];
//var dir2 = location.pathname;
if (dir == "agriculture/harvest")
document.write('<IMG SRC="/images/ib_agriculture_harvest.jpg" WIDTH=1024 HEIGHT=91 BORDER=0>')
else if (dir == "showcase")
var dir = location.pathname.split("/")[1];
//var dir2 = location.pathname;
if (dir == "harvest")
document.write('<IMG SRC="/images/ib_agriculture_harvest.jpg" WIDTH=1024 HEIGHT=91 BORDER=0>')
else if (dir == "showcase")
上面的两个脚本都继续抓取foo.com/agriculture banner(ib_agriculture.jpg),而不是名为foo.com/agriculture/harvest(ib_agriculture_harvest.jpg)。我不知道如何让脚本每页调用适当的横幅。
答案 0 :(得分:0)
当你调用pathname.split时,你得到一个这样的数组:
["foo.com", "agriculture", "harvest"]
然后取出索引为1的项目并将其放入dir
变量:
var dir = location.pathname.split("/")[1]
所以dir
的价值是“农业”,即使“收获”也是网址的一部分。要检查该字符串,您需要使用location.pathname.split("/")[2]
。
或者你可以这样做:
var parts = location.pathname.split("/");
var dir = parts[1];
if (parts.length > 2)
{
dir += "/" + parts[2];
}
if (dir == "agriculture/harvest")
document.write('<IMG SRC="/images/ib_agriculture_harvest.jpg" WIDTH=1024 HEIGHT=91 BORDER=0>')