分配内部页面横幅交换

时间:2012-11-13 17:57:24

标签: javascript jquery

该部分是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)。我不知道如何让脚本每页调用适当的横幅。

1 个答案:

答案 0 :(得分:0)

你应该知道的第一件事是:

var segments = "/agriculture/harvest".split('/');
console.log(segments);  // ["", "agriculture", "harvest"]

有很多方法可以解决这个问题,但是这种方法可以让大部分代码保持不变:

var dirs = location.pathname.split('/');

if (dirs[1] == 'agriculture') {
    if (dirs[2] == 'harvest')
        ; // set harvest banner
    else
        ; // set agriculture banner
} else if (dirs[1] == 'showcase')
    ; // set showcase banner
else if (dirs[1] == 'contact')
    ; // set contact banner
// etc..

还有另一种方式,更具说明性。您可以构建包含路径名模式和图像名称的对象。然后你循环它并进行第一场比赛。这样,您可以添加任意多个,而无需编写更多代码:

var banners = {
    "^/agriculture/harvest": "ib_agriculture_harvest.jpg",
    "^/agriculture": "ib_agriculture.jpg",
    "^/showcase": "ib_showcase.jpg",
    "^/contact": "ib_contact.jpg"
    // as many more as you need
};

for( var pattern in banners ) {
    var regex = new RegExp(pattern);
    if (regex.test(location.pathname)) {
        document.write('<IMG SRC="/images/'+banners[pattern]+'" WIDTH=1024 HEIGHT=91 BORDER=0>');
        break;
    }
}