http://jsbin.com/cunejafehe/edit?html,js,控制台,输出
var reg = /^[a-zA-Z\d\s\-'#(),"]*$/;
function myFunction(e){
console.log(e.value);
if(reg.test(e.value))
{
return false;
}
}
<input onkeyup="myFunction(this)" type="text">
我想知道为什么上面的代码行不通,我想做的是只允许这些字符出现在输入中:a-z
并且1-9
包括0
,以及这些字符-'#(),"
请看看这种方法。在这里,我传递了一个event
对象而不是DOM元素引用,然后针对Regx表达式对其进行了检查。
var reg = /^[a-zA-Z\d\s\-'#(),"0-9]*$/
function myFunction(e){
var c = String.fromCharCode(e.which)
console.log(c);
if(reg.test(c))
{
return true;
}
else
return false;
}
$(document).ready(function(){
$( "#mytextbox" ).keypress(function( e) {
return myFunction(e);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Inline function : <input onkeypress="return myFunction(event)" type="text">
<br/>
Binding a function : <input id="mytextbox" type="text">
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句