2016-04-11 64 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); 
相关问题