1

我目前单独搜索 window.location.href :

window.location.href:http://www.example.com/6CATA/folder/file.html

var searchWinHref = window.location.href;
if(searchWinHref.indexOf("/6CATA/") > -1) {
  alert('6CATA is in the window.location.href');
}

这会触发警报。

如何调整它以查询变量 searchWinHref 以匹配数组中的字符串之一?

var searchWinHref = window.location.href;
var searchWinArray = ['6CATA', '6CATB', '6CATC'];
if(searchWinHref.indexOf(searchWinArray)) {
  alert('alert which code is in the window.location.href');
}
4

4 回答 4

3

如果您的目标是更新的浏览器:(IE9+)

var isMatch = ['6CATA', '6CATB', '6CATC'].some(function(value) {
    return window.location.href.indexOf( value ) !== -1;
});

if ( isMatch ) {
    // do my alert stuff
}

查看更多关于Array.some

支持:

"Feature         Chrome   Firefox (Gecko)   Internet Explorer   Opera   Safari
 Basic support   (Yes)    (Yes)             9                   (Yes)   (Yes) 
于 2012-11-13T15:48:41.010 回答
2

使用 for 循环:

var searchWinHref = window.location.href;
var searchWinArray = ['6CATA', '6CATB', '6CATC'];
for(var i = 0; i < searchWinArray.length; i++) {
  if(searchWinHref.indexOf(searchWinArray[i]) != -1) {
     alert(searchWinArray[i]);
     break;  // stop if we found one..
  }
}

如果您想发挥创意,可以利用jQuery .each() API

jQuery.each(searchWinArray, function() {
  //  `this`  now points to the current item in the array  
  if(searchWinHref.indexOf(this) != -1) {
     alert(this);
     return false;   // stop iterating if we found it
  }       
});
于 2012-11-13T15:43:42.863 回答
2
  var searchWinHref = window.location.href;
  var searchWinArray = ['6CATA', '6CATB', '6CATC'];
  var result = [];
  for(var i=0; i<searchWinArray.length; i++)
  {
     if(searchWinHref.indexOf(searchWinArray[i])) {
        result.push(searchWinArray[i]);
     }
  }
  alert(result.join(","));
于 2012-11-13T15:46:39.020 回答
1

尝试

var href = window.location.href, s = ['6CATA', '6CATB', '6CATC'], i = s.length;

while( --i ) {
    if( href.indexOf( s[i] ) > -1 ) { 
        alert( "found" );
        break;
    }
}
于 2012-11-13T16:02:45.563 回答