使用javascript根据URL添加不同的文本

时间:2012-03-22 12:51:16

标签: javascript url text add

您好,我需要做一些我认为有点复杂的事情。

我需要根据URL添加不同的文本到DIV,我知道每种情况下的URL是什么(有6个),所以我需要javascript(jquery)来做这个我刚刚知道如何自己做。

谢谢,戴夫。

 <script type = "text/javascript">
 function showDiv() {
 var url = window.location.href;
 if (/(Electric-Mobility)/i.test(url)) {
 document.getElementById("content_hide").style.display="none";
 }
 else {
 document.getElementById("content_hide").style.display="block";
 }
  }
 </script>
 <body onload = "showDiv()" >    

这种作品但不能做我想要的,也可以在页面加载后做。

这些是URL     ../brands/Electric-Mobility.html?sort=priceasc     ../brands/Pride.html?sort=priceasc     ../brands/Medical.html?sort=priceasc     ../brands/Princey.html?sort=priceasc     ../brands/NHC.html?sort=priceasc     ../ Roma.html?排序= priceasc

每个网址的

我需要div中的不同文字#content_hide

希望这更清楚

由于     新代码

    <script type="text/javscript">
    function showDiv() {
    var url = window.location.href;

    if (/(Electric-Mobility)/i.test(url)){

    // i changed your old script using jQuery
    $("#content_hide").css("display","none");
     } else {
   $("#content_hide").css("display","block");
   }


   var myURL = url.split('?');
    var myTexts = ["text1","text2","text3"];
     switch(myURL[0]){
        case "http://www.youngsmobility.co.uk/brands/Electric-Mobility.html":
         $("#content_hide").html(myTexts[0]);
     break;
      case "http://www.youngsmobility.co.uk/brands/Pride.html":
     $("#content_hide").html(myTexts[1]);
      break;
     }
     } 
   </script>

    <body onload = "showDiv()" >

将日期更新为代码             

     function showDiv() {
    var url = window.location.href;
    var myURL = url.split('?');
    var myTexts = ["text1","text2","text3"];
     switch(myURL[0]){
     case "www.youngsmobility.co.uk/brands/Electric-Mobility.html":
     $("#content_hide").html(myTexts[0]);
     break;
     case "www.youngsmobility.co.uk/brands/Pride.html":
     $("#content_hide").html(myTexts[1]);
     break;
    }
     } 
     </script>

   <body onload = "showDiv()"

2 个答案:

答案 0 :(得分:3)

switch(location.href) {
    case "http://example.com/page1":
        // put text for page1 in div
        break;
    // add more cases as needed
    // optionally add a default case.
}

这应该让你去。

答案 1 :(得分:1)

function showDiv() {
    var url = window.location.href;
    if (/(Electric-Mobility)/i.test(url)){

    // i changed your old script using jQuery
    $("#content_hide").css("display","none");
    } else {
    $("#content_hide").css("display","block");
    }
    // my script start here
    var myURL = url.split('?');
    var myTexts = ["text1","text2","text3"];

    switch(myURL[0]){
     case "url1.html":
         $("#div_id").html(myTexts[0]);
     break;
     case "url2.html":
         $("#div_id").html(myTexts[1]);
     break;
    }
}