我必须在我正在实施的网站上实现邮政编码查找。在地址表格上,有一个邮政编码字段。当用户键入后置代码并导航到下一个字段时,将对API进行REST调用以获取与该后置代码关联的城市和州。然后我使用jQuery在相应的字段中填写这些值。
我们在某些情况下,某个邮政编码可以属于两个不同的城市(在同一个国家/地区内),我们需要处理这些问题。代码如下:
$.getJSON(requestUrl, function (json) {
// Clear the list
$(postCodeList).empty();
if (!json) {
return;
}
if (json.length > 1) {
// Fill the list with cities
for (var i = 0; i < json.length; i++) {
var item = document.createElement("li");
item.setAttribute("data-canton", json[i].canton);
item.appendChild(document.createTextNode(json[i].city));
if (json[i].plz === parseInt(plz, 10)) {
postCodeList.appendChild(item);
}
}
// Append the list
var wrapperDiv = $citySelector.parent();
$(postCodeList).css("z-index", 100);
$(wrapperDiv).append(postCodeList).focus();
// Handle onClick on suggested city
$("#post-code-list li").on("mousedown touchend", function (evt) {
var suggestedCity = $(this).text();
var suggestedCanton = this.getAttribute('data-canton');
$cantonSelector.val(suggestedCanton).focus().trigger("input").trigger("blur");
$citySelector.val(suggestedCity).focus().trigger("input").trigger("blur").focus();
$("#post-code-list").hide();
evt.preventDefault();
});
} else {
// Don't return an array in this case
if (json.plz === parseInt(plz, 10)) {
$cantonSelector.val(json.canton).focus().trigger("input").trigger("blur");
$citySelector.val(json.city).focus().trigger("input").trigger("blur").focus();
$("#post-code-list").hide();
}
}
});
如果我们收到一个数组(json.length > 1
),我们的代码完全按预期工作。相关部分是:
$cantonSelector.val(suggestedCanton).focus().trigger("input").trigger("blur");
$citySelector.val(suggestedCity).focus().trigger("input").trigger("blur").focus();
需要链focus().trigger("input").trigger("blur")
来触发验证,这就是如何设置parsley。
现在,我们来看一下我们收到单个值json.length <= 1
的情况。在这种情况下,我们执行以下代码:
$cantonSelector.val(json.canton).focus().trigger("input").trigger("blur");
$citySelector.val(json.city).focus().trigger("input").trigger("blur").focus();
代码完全相同。但是,在这种情况下,我们遇到以下问题。
铬
Safari浏览器
火狐
预期的行为是,州和城市都被填写,州区域被验证并且焦点(和光标)保留在城市场地上。这适用于桌面,但不适用于移动设备。
有人可以解释一下我做错了什么吗?
由于