javascript - Jquery表单提交没有被触发

标签 javascript jquery performance debugging

我是 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/

相关文章:

javascript - 将元素移动到右侧 Javascript

javascript - 在 jquery 上动态编写点击事件

javascript - 检查类或添加类,哪个性能更好

performance - 为什么某些资源在 Visual Studio 编译期间没有达到 100%?

javascript - 如何在 Angular 2中将参数传递给POST方法

c# - 经过身份验证的调用

javascript - 语法错误 : expected expression, 获取关键字 'else'

jquery - 如何创建一个不打扰 css 选择器的动态 html 包装器元素

javascript - 使用 var $this = $(this); 是否可以接受?还是有更好/更可接受的方式?

asp.net-mvc - 提高 ASP.NET MVC 启动性能