2012-05-10 146 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