我是 JavaScript 新手。我一直在尝试设计一些代码,当点击搜索按钮时对位置进行地理编码,如果成功则提交表单。为了使其稍微复杂一些,如果选择了自动建议中的选项,它甚至会在点击搜索按钮之前对其进行地理编码。
这一切似乎都有效,只是表单从未提交,而且我不明白为什么。
链接:http://jsfiddle.net/sR4GR/42/
$(function () {
var input = $("#loc"),
lat = $("#lat"),
lng = $("#lng"),
lastQuery = null,
lastResult = null, // new!
autocomplete;
function processLocation(query, callback) { // accept a callback argument
var query = $.trim(input.val()),
geocoder;
// if query is empty or the same as last time...
if( !query || query == lastQuery ) {
callback(lastResult); // send the same result as before
return; // and stop here
}
lastQuery = query; // store for next time
geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: query }, function(results, status) {
if( status === google.maps.GeocoderStatus.OK ) {
lat.val(results[0].geometry.location.lat());
lng.val(results[0].geometry.location.lng());
lastResult = true; // success!
} else {
alert("Sorry - We couldn't find this location. Please try an alternative");
lastResult = false; // failure!
}
callback(lastResult); // send the result back
});
}
autocomplete = new google.maps.places.Autocomplete(input[0], {
types: ["geocode"],
componentRestrictions: {
country: "uk"
}
});
google.maps.event.addListener(autocomplete, 'place_changed', processLocation);
$('#searchform').on('submit', function (event) {
var form = this;
event.preventDefault(); // stop the submission
processLocation(function (success) {
if( success ) { // if the geocoding succeeded, submit the form
form.submit()
}
});
});
});
最佳答案
您正在调用:
processLocation(function (success) {
但是您的 processLocation 在第二个参数上有回调:
function processLocation(query, callback)
尝试从 processLocation 中删除查询参数:
function processLocation(callback)
或使用空白参数调用它:
processLocation(null, function (success)
关于javascript - Jquery表单提交没有被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16611972/