2012-10-04 32 views
0

我确定这很容易,我也看到了类似的问题,但没有人帮助我弄清楚为什么这不起作用。难道没有人告诉我为什么当currentPage被设置为faqcontact时不能捕捉到?Javascript如果使用或者

<script type="text/javascript"> 
       function init() { 
       document.getElementById('searchSubmit').onclick=function(){ 
         var uriArgs = window.location.search; 
         var currentPage = uriArgs.match(/page=?(\w*)/); 
         if ((currentPage == null) || (currentPage == 'faq') || (currentPage == 'contact')) { 
           currentPage = "index"; 
           document.getElementById('searchHidden').value = currentPage; 
         } 
         else { 
           document.getElementById('searchHidden').value = currentPage[1]; 
         } 
       } 
       } 
       window.onload=init; 
     </script> 

我设定一个警报弹出,所以我可以看它是否被正确地被设置为faqcontact,它是如此,我不知道为什么if语句不会轻松没收。

感谢先进!

回答

2

如果匹配,String.match将返回数组索引1处的捕获组。例如:

> 'page=sdfsfsdf'.match(/page=?(\w*)/) 
["page=sdfsfsdf", "sdfsfsdf"] 

所以你需要寻找内通过match返回的数组(假设它不是null)。

if (currentPage == null || currentPage[1] == 'faq' || currentPage[1] == 'contact') { 
    /* ... */  
} 
+0

omg我不知道为什么这总是发生在我身上,但我只是意识到,我发布这个问题后。感谢您的帮助。它现在有效。 – Dylan

0

你的问题是不是与if语句来,但随着match method的结果:它返回匹配和匹配组阵列 - 要比较的第一个匹配的组。

var match = window.location.search = uriArgs.match(/page=?(\w*)/), 
    currentPage = false; 
if (match != null) 
    currentPage = match[1]; 

if (!currentPage || currentPage=='faq' || currentPage=='contact') { 
    // do something 
}