2012-05-10 104 views
15

林很确定我的语法这个错误,因为脚本只适用于字符串匹配“视频”,如果字符串有“字”音频“它被忽略。的 “#” 重定向的 “../../../index.html” 不工作的值。多个字符串与indexOf匹配()

JS

var ua = navigator.userAgent.toLowerCase(); 
var isIE8 = /MSIE 8.0/i.test(ua); 
if (isIE8) { 
    $('a').click(function() { 
     var srcTag = $(this).find('img').attr('src'); 
     if (srcTag.indexOf('Video' || 'Audio') > -1) { 
      if (confirm('Download Safari? \n\n http://apple.com/safari/download/')) { 
      window.location = 'http://apple.com/safari/download/'; 
      } else { window.location = '../../../index.html';} 
     } else { 
      alert('no match'); 
     } 
    }); 
} 

HTML

<a href="#"><img src="Video/000_Movies/assets/005_CCC_Jesus_Story_80x60.jpg" />test1</a> 
<a href="#"><img src="Audio/000_Movies/assets/006_GSP_Gods_Story_80x60.jpg" />test2</a> 
<a href="#"><img src="Media/000_Movies/assets/002_God_Man_80x60.jpg" />test3</a> 
+1

srcTag.indexOf( '视频')> -1 || srcTag.indexOf('Audio')> -1 –

+0

尝试使用此部分的绝对网址: window.location ='../../../index。html' – bygrace

+0

它需要是一个相对的URL,因为它将在本地运行,并且无法知道用户驱动的字母是什么。 – Blainer

回答

61

把它变成正则表达式要短得多。

if (srcTag.match(/(video|audio)/)) { 
    /* Found */ 
} else { 
    /* Not Found */ 
} 

请注意,请不要做你正在尝试做的事情。要求用户在使用Internet Explorer 8时下载Safari会对互联网以及该用户造成损害。

至于域名重定向到另一个位置,你应该使用.preventDefault()保持浏览器的链接如下:

$("a.videoDownload").on("click", function(e){ 
    e.preventDefault(); 
    if (this.getElementsByTagName("img")[0].src.match(/(video|audo)/)) { 
    window.location = confirm('Download Safari?') 
     ? "http://apple.com/safari/download" 
     : "../../../index.html" ; 
    } else { 
    /* No match */ 
    } 
}); 

再次,请不要实际上做到这一点。没有人想要那家伙,当你告诉用户下载另一个浏览器时,你是那家伙

+2

/(video | audio)/ .test(srcTag)对我更好看。 –

+0

这工作完美。我更新了我的OP。 – Blainer

+0

isnt str.indexOf('string')比正则表达式快吗? – qodeninja

3

我想你需要是2个独立的indexOf像下面那样,

srcTag.indexOf('Video') != -1 || srcTag.indexOf('Audio') != -1 
2

是的,你需要像这样做:

if (srcTag.indexOf('Video') > -1 || srcTag.indexOf('Audio') > -1) { 
+0

+1 indexOf快于regEx – qodeninja

+1

@qodeninja:只有一个字符串,但针对多个'indexOf()'搜索,比如上面的'test()'(正则表达式)变得更高效](https://jsperf.com/zotero/1) – Wolf

4

我想你可能想的indexOf外的OR(||)运算符像这样:

if ((srcTag.indexOf('Video') !== -1) || (srcTag.indexOf('Audio') !== -1)) { 
    ... 
} 
5

'Video' || 'Audio'是逻辑OR。非空字符串在JavaScript中是隐含的真值,因此短路OR不会被评估,并且这会折叠到只有'Video'。这就是为什么你看到你做的结果。

其他人指出你正确的方向来解决。

+0

谢谢你真正解释他的错误在哪里,为什么**它导致错误 –

0

这也将工作:

if (srcTag.indexOf('Video') >= -1 || srcTag.indexOf('Audio') >=-1) { 
+0

它总是大于或等于-1? –

-1

这为我工作:与正则表达式

if (srcTag.indexOf('Video' | 'Audio') >= -1) { 
+0

从字面上看,总是返回true,不管是什么https://jsfiddle.net/6rnaoa0u/ – Liam

+0

您应该阅读一下[按位运算符是什么](https://developer.mozilla.org/en-US/docs /网络/的JavaScript /参考/运营/ Bitwise_Operators) – Liam

0

其相当快,并曾与XRegExp更好。

var sourceString = 'hello world, i am web developer'; 
if (XRegExp.test(sourceString, /(hello|web)/)) { 
    // yes, `hello` or `web` is found in `sourceString` 
} 

执行时间为0.10595703125ms