2016-04-11 65 views
2

我有一個輸入html元素,我在jquery中使用模糊函數來檢查值是否包含特定元素,但我的代碼不工作。檢查數組中的字符是否存在於字符串中出錯

jQuery("#email").blur(function() { 
... 
var arr = ["1","6","7"]; 
if(this.value()){ // check if the string value contains characters in arr Array 
.. 

有什麼想法嗎? 我也試過用indexOf(),但仍然沒有工作

} ...

...

+1

你怎麼使用'indexOf','THIS.VALUE()'是錯誤的,它應該只是' this.value' –

+0

既然你想通過字符檢查字符,你可能不得不使用'keypress'事件 –

+0

我不能使用按鍵一些Android設備無法識別它 – gadss

回答

2

您可以使用some組合和indexOf

jQuery("#email").blur(function() { 
    var arr = ["1","6","7"]; 
    // Check if string contains characters above 
    var charactersInString = arr.some(function(chr) { 
    return this.value.indexOf(chr) >= 0; 
    }); 

    // charactersInString will be true if any of the 
    //characters in the array are in the input string 
}); 
0

希望這個片段將是有用的

// Defining array of predefined chars outside the blur event. 
// No need to define it on every blur event. 
var arr = ["1","6","7"]; //array of predefined chars. 
$("#email").blur(function(event) { // Expecting an input element 
var _getText = $(this).val(); // get the value from input 
for(var i = 0;i<arr.length;i++){ // loop through array of predefined chars 
    // use indexOf to check if input val 
    //contain any of predefined chars 
    if(_getText.indexOf(arr[i]) ==-1){ 
    console.log(arr[i] + " is not present in the string"); 
    } 
    else{ 
    console.log(arr[i]+ " is present in the string"); 
    } 
} 
}) 

Jsfiddle

0

我有不同的方法,我希望會有很大的幫助:

(function($) { 
    var arr = ["1","6","7"]; 

    $(document).ready(function() { 
     var email = document.getElementById("email"); 
     var lastCharacter; 

     email.addEventListener("input", function(e) { 
      lastCharacter = this.value.substr(-1); 

      for (var i = 0; i < arr.length; i++) { 
       if (arr[i] === lastCharacter) { 
        console.log("Exist - Contains an specific element of the Arr"); 
       } 
      } 

     }, false); 

    }); 

})(jQuery); 
相關問題