2012-11-16 91 views
1

我有一個包含一些值的數組。我想如果文本框的值包含任何數組的元素,它會顯示警告「存在」的值,否則「不存在」 我曾嘗試下面的代碼:如何在jquery中使用包含數組的函數?

$('[id$=txt_Email]').live('blur', function (e) { 
    var email = $('[id$=txt_Email]').val(); 
    var array = ['gmail.com', 'yahoo.com']; 
    if (array.indexOf(email) < 0) { // doesn't exist 
     // do something 
     alert('doesnot exists'); 
    } 
    else { // does exist 
     // do something else 
     alert('exists'); 
    } 

}); 

但是,這是將整個值與數組的元素進行比較。我想使用包含函數,因爲我們可以在C#中使用string.Please幫助我。 我想如果用戶鍵入「[email protected]」它將顯示存在數組中。如果用戶輸入「[email protected]」,它將提醒不存在。

回答

2

要找到匹配不準確的字符串,你需要做一些事情像

Live Demo

arr = ['gmail.com', 'yahoo.com']; 

alert(FindMatch(arr, 'gmail.co')); 

function FindMatch(array, strToFind) 
{ 

    for(i=0; i < array.length; i++) 
    { 
     if(array[i].indexOf(strToFind) != -1) 
      return true;   
    } 
    return false; 
} 
​ 
+0

InArray會匹配整個值而不是一些字符,請再次檢查我的問題,我已經更新。 – Ram

+0

更新我的答案,看看。 – Adil

3

我想你想

$.each(array, function() { 
    found = this.indexOf(email); 
}); 
1
$(document).on('blur', '[id$=txt_Email]', function (e) { 
    var email = this.value, array = ['gmail.com', 'yahoo.com']; 

    if (email.indexOf('@')!=-1) { 
     if ($.inArray(email.split('@')[1], array)!=-1) { 
      alert('exists'); 
     }else{ 
      alert('does not exists');   
     } 
    } 
});​ 

FIDDLE

0
b is the value, a is the array 

It returns true or false 



function(a,b){return!!~a.indexOf(b)} 
相關問題