Jquery检查数组执行函数

我正在创建一个需要非常小的邮政编码检查器的网站。 我在arrays中有大约8个邮政编码前缀,HX,HD,BD,LS等。 我也有一个简单的输入字段并提交btn。 当用户键入例如HX5 9DU的邮政编码时,我希望Jquery检查数组,如果前2/3字母匹配,我希望div显示消息时淡入淡出。

我该怎么办? 提前谢谢了。

这是一种方法:

http://jsfiddle.net/uNKhs/3/

HTML:

some message

jQuery的:

 $(function() { // Wrap the code such that it will run after document loads $("#message").hide(); // First hide the message var prefix = ['HX', 'HD', 'BD', 'LS']; // Create your array of prefixes $('#myInput').keyup(function(e) { // Trigger an event handler on each 'keyup' var value = $(this).val(); // Grab the current value of the input // Store first two characters in a variable, and convert to upper case var firstTwo = value.substr(0,2).toUpperCase(); // Check that the length of the input is greater than one, // and that the firstTwo characters are in the prefix array if(value.length > 1 && ($.inArray(firstTwo, prefix) >= 0)) { // If so, find the hidden element with ID "message" and fade it in. $("#message:hidden").fadeIn(); } }); }); 

一些相关的jQuery文档:

.hide() http://api.jquery.com/hide/

$.inArray() http://api.jquery.com/jQuery.inArray/

.fadeIn() http://api.jquery.com/fadein/

.keyup() http://api.jquery.com/keyup/

.val() http://api.jquery.com/val/


编辑:

运行jQuery代码时,通常最好在文档加载后运行代码。 你可以通过几种不同的方式做到这一点。

 $(document).ready(function() { // My jQuery code }); 

要么

 $(function() { // My jQuery code }); 

这两个人将完成同样的事情。

我更新了我的答案,包括第二个版本。


奖金:

如果用户为前两个字符键入小写字符,则此版本将使用大写版本更新输入。

编辑:此外,如果找不到数组中的匹配,它会显示失败消息。

http://jsfiddle.net/uNKhs/8/

 $(function() { $("#message").hide(); $("#fail").hide(); var prefix = ['HX', 'HD', 'BD', 'LS'] $('#myInput').keyup(function(e) { var value = $(this).val(); var firstTwo = value.substr(0,2); var firstTwoUpper = firstTwo.toUpperCase(); if(firstTwo != firstTwoUpper) { $(this).val( value.replace(/^\w\w/, firstTwoUpper) ); } if(value.length > 1) { if($.inArray(firstTwoUpper, prefix) >= 0) { $("#fail").hide(); $("#message:hidden").fadeIn(); } else { $("#message").hide(); $("#fail:hidden").fadeIn(); } } else { $("#message").hide(); $("#fail").hide(); } }); });​ 

我想如果你让一些服务器端演员参与到这一集中,那将是最好的。

做类似的事情:

 $.getJSON('/CheckPrefix', { query = $('#prefixInpunt').val() }, function(responseMsg) { $('#messageDiv').show().html(responseMsg); }) 

您可以将所有代码存储在数据库中,然后使用您在json调用中获得的参数查询数据库,并在服务器上制作消息并将其发送到UI。