我还在学习jQuery,我在网上提到了一些教程。我从这个网站获得了我的代码并将其插入JSFiddle以尝试但它没有用:
HTML
<input id="mytextbox" style="width:300px" placeholder="Only English letters are allowed here...">
JS
$("#mytextbox").on("keypress", function(event) {
// Disallow anything not matching the regex pattern (A to Z uppercase, a to z lowercase and white space)
// For more on JavaScript Regular Expressions, look here: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
var englishAlphabetAndWhiteSpace = /[A-Za-z ]/g;
// Retrieving the key from the char code passed in event.which
// For more info on even.which, look here: http://stackoverflow.com/q/3050984/114029
var key = String.fromCharCode(event.which);
//alert(event.keyCode);
// For the keyCodes, look here: http://stackoverflow.com/a/3781360/114029
// keyCode == 8 is backspace
// keyCode == 37 is left arrow
// keyCode == 39 is right arrow
// englishAlphabetAndWhiteSpace.test(key) does the matching, that is, test the key just typed against the regex pattern
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39 || englishAlphabetAndWhiteSpace.test(key)) {
return true;
}
// If we got this far, just return false because a disallowed key was typed.
return false;
});
$('#mytextbox').on("paste",function(e)
{
e.preventDefault();
});
我使用的框架是 No-Library(纯JS),扩展名设置为 onload 。
然而,这个脚本似乎适用于我所提及的网站。我可以知道我做错了吗?是不是我没有包含一些jQuery库?
答案 0 :(得分:5)
作为一个框架,你需要选择一个jQuery版本(例如 jQuery 2.1.0 )而不是 No-Library(纯JS)。
如果不这样做,jQuery库将不会被加载,因此你的jQuery相关代码将不起作用。
答案 1 :(得分:2)
您必须包含jquery文件并使用它
$("#mytextbox").on("keypress", function(event) {
// Disallow anything not matching the regex pattern (A to Z uppercase, a to z lowercase and white space)
// For more on JavaScript Regular Expressions, look here: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
var englishAlphabetAndWhiteSpace = /[A-Za-z ]/g;
// Retrieving the key from the char code passed in event.which
// For more info on even.which, look here: http://stackoverflow.com/q/3050984/114029
var key = String.fromCharCode(event.which);
//alert(event.keyCode);
// For the keyCodes, look here: http://stackoverflow.com/a/3781360/114029
// keyCode == 8 is backspace
// keyCode == 37 is left arrow
// keyCode == 39 is right arrow
// englishAlphabetAndWhiteSpace.test(key) does the matching, that is, test the key just typed against the regex pattern
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39 || englishAlphabetAndWhiteSpace.test(key)) {
return true;
}
// If we got this far, just return false because a disallowed key was typed.
return false;
});
$('#mytextbox').on("paste",function(e)
{
e.preventDefault();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="mytextbox" style="width:300px" placeholder="Only English letters are allowed here...">
&#13;
答案 2 :(得分:1)