【发布时间】:2010-05-24 11:00:16
【问题描述】:
我正在创建一个需要非常小的邮政编码检查器的网站。我在一个数组中有大约 8 个邮政编码前缀、HX、HD、BD、LS 等。我还有一个简单的输入字段并提交 btn。当用户输入邮政编码(例如 HX5 9DU)时,我希望 Jquery 检查数组,如果前 2/3 字母匹配,我希望 div 淡入显示消息。
我该怎么做?非常感谢。
【问题讨论】:
我正在创建一个需要非常小的邮政编码检查器的网站。我在一个数组中有大约 8 个邮政编码前缀、HX、HD、BD、LS 等。我还有一个简单的输入字段并提交 btn。当用户输入邮政编码(例如 HX5 9DU)时,我希望 Jquery 检查数组,如果前 2/3 字母匹配,我希望 div 淡入显示消息。
我该怎么做?非常感谢。
【问题讨论】:
这是一种方法:
HTML:
<div id="message">some message</div>
<input type="text" id="myInput" />
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
});
两者将完成相同的事情。
我更新了我的答案以包含第二个版本。
奖励:
如果用户为前两个字符键入小写字符,此版本将使用大写版本更新输入。
编辑:此外,如果未找到数组中的匹配项,则会显示失败消息。
$(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();
}
});
});
【讨论】:
firstTwo 中存储的值转换为大写。 var firstTwo = value.substr(0,2).toUpperCase(); 应该照顾你。我也更新了 jsFiddle 链接。
我想最好让一些服务器端演员参与这一集。
做类似的事情:
$.getJSON('/CheckPrefix', { query = $('#prefixInpunt').val() }, function(responseMsg) {
$('#messageDiv').show().html(responseMsg);
})
您可以将所有代码存储在一个数据库中,然后使用您在 json 调用中获得的参数查询该数据库,并在您的服务器上制作消息并将其发送到 UI。
【讨论】: