0

此函数通过 HTML 表单从最终用户接收两条数据,“#from”和“#to”。我希望它们来自设置变量,而不是用户输入(即#directions-form')。我该怎么做呢?

$('#directions-form').submit(function(e) {
  $('#error').hide();
  ds.route({
    origin: $('#from').val(),
    destination: $('#to').val(),
    travelMode: $('#mode').val()
  }, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      fitBounds = true;
      dr.setDirections(result);
    }
    else {
      $('#error').text(status).show();
    }
    recalcHeight();
  });
  e.preventDefault();
  return false;
});
4

2 回答 2

1

下面将去除UI元素和回调之间的耦合

var to = $('#to').val();// or some arbitrary other source that contains the value you want to assign
var from = $('#from').val();
$('#directions-form').submit(function(e) {
  $('#error').hide();
  ds.route({
    origin: from,
    destination: to,
    travelMode: $('#mode').val()
  }, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      fitBounds = true;
      dr.setDirections(result);
    }
    else {
      $('#error').text(status).show();
    }
    recalcHeight();
  });
  e.preventDefault();
  return false;
});
于 2013-09-12T00:12:51.977 回答
1

您需要做的就是用变量替换值。例如,它可能看起来像这样:

origin: myOrigin,
destination: myDestination,

就目前而言,代码本身并没有什么特别之处。这一切都在做:

$('#from').val()

从名为from. 这就像变量一样评估为一个值,它只是不将该值存储在变量中,而是直接从 HTML 中获取它。您可以直接将其替换为变量。

Update: In your PasteBin in the comments below is looks like you're calling the function incorrectly here:

ds.route(from,to,mode);

That function takes two parameters, the first of which is an object composed of the three values you're trying to pass to it and the second is the callback function. Something like this:

ds.route({
  origin: from,
  destination: to,
  travelMode: mode
}, function(result, status) {
  // Here you can respond to the results in some way
});
于 2013-09-12T00:14:01.217 回答