开发者

multiple links in if statement

I have a script that specifices that a certain element does not be shown whe开发者_开发技巧n on a specific page. Below is the code I used:

   <script type="text/javascript">
   function callOnPageLoad()
   {
   var url = window.location.href;
   if(url == "http://www.exampledomain.com")
   {
   document.getElementById('rolex').style.display = 'none';
   }
   }
   </script>     

However I need to put a few more url's in the if statement, what is the right way of doing this?

Many thanks


I preffer to generate associative array and then check if string is set. It can be obtained from AJAX, from different script etc. and isn't hradcoded into if

   <script type="text/javascript">
   var urlArray = { "http://www.exampledomain.com" : true, "http://www.exampledomain.com/foobar.html" : true };
   function callOnPageLoad()
   {
   var url = window.location.href;
   if( urlArray[url] )
   {
   document.getElementById('rolex').style.display = 'none';
   }
   }
   </script>     


if(url == "http://www.exampledomain.com" || url == "http://www.anotherdomain.com")
{
}


Add more conditions in the if block:

   <script type="text/javascript">
   function callOnPageLoad()
   {
   var url = window.location.href;
   if(url == "http://www.exampledomain.com" || url == "anotherurl" || url == "andanother")
   {
   document.getElementById('rolex').style.display = 'none';
   }
   }
   </script>


have an array of urls and iterate

function callOnPageLoad()
{
   var urls = [
      "http://www.exampledomain.com",
      "http://www.exampledomain2.com"
   ];
   var url = window.location.href;
   for ( var i=0; i < urls.length; i++ ) {
      if(url == urls[i])
      {
          document.getElementById('rolex').style.display = 'none';
          break;
      }
   }   

}


you can create an array of those urls and run for loop thought them, this will be more dynamic approach to your problem.

using long if statements is not advisible because you can loose a character here or a bit of logic there

If your urls point to external urls or match other patterns that you can distinguish them from other urls you can use it without an array.


 function callOnPageLoad(type)

    {
        var url = window.location.href;
             var urls=new array("http://www.exampledomain1com","http://www.exampledomain2.com");    


        if(url in urls){
            document.getElementById('rolex').style.display = 'none';
        }
    }


if(url == "http://www.exampledomain.com" || url =="http://www.url2.com" || url == "http://www.url3.com") and so forth ... ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜