设置变量而不是用户输入

时间:2013-09-12 00:05:59

标签: javascript api function variables

此功能通过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;
});

2 个答案:

答案 0 :(得分: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;
});

答案 1 :(得分:1)

您需要做的就是用变量替换值。例如,它可能如下所示:

origin: myOrigin,
destination: myDestination,

目前的代码并没有什么特别之处。这一切都在做:

$('#from').val()

从名为from的表单上的输入元素动态获取值。这会像变量一样计算为一个值,它只是不将该值存储在变量中,而是直接从HTML中获取它。您可以直接用变量替换它。

更新:在下面的评论中,您的PasteBin看起来就像是在这里错误地调用了这个函数:

ds.route(from,to,mode);

该函数有两个参数,第一个是由你试图传递给它的三个值组成的对象,第二个是回调函数。像这样:

ds.route({
  origin: from,
  destination: to,
  travelMode: mode
}, function(result, status) {
  // Here you can respond to the results in some way
});