Javascript 设置变量而不是用户输入

Javascript 设置变量而不是用户输入,javascript,api,function,variables,Javascript,Api,Function,Variables,此函数通过HTML表单“#from”和“#to”从最终用户接收两条数据。我希望它们来自设置变量,而不是用户输入(即#方向表单”)。我该怎么做呢 $('#directions-form').submit(function(e) { $('#error').hide(); ds.route({ origin: $('#from').val(), destination: $('#to').val(), travelMode: $('#mode').val() },

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

$('#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;
});

下面将移除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;
});

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

origin: myOrigin,
destination: myDestination,
ds.route({
  origin: from,
  destination: to,
  travelMode: mode
}, function(result, status) {
  // Here you can respond to the results in some way
});
目前的代码没有什么本质上的特殊之处。所有这些都在做:

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

更新:在你的粘贴箱中,下面的评论是:看起来你在这里错误地调用了函数:

ds.route(from,to,mode);
该函数接受两个参数,第一个是一个对象,由您试图传递给它的三个值组成,第二个是回调函数。大概是这样的:

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

请重新措辞,因为您当前的问题不清楚。我只是重新措辞,它更有意义吗?然后我可以将var设置为=lat | long和var from=lat | long,这应该可以解决我的问题。在分配这两个变量时,您可以应用您想要的任何逻辑。最终结果将分配给始发地和目的地属性,我按照建议执行了分配,但该函数仍然依赖于(“#方向表单”)。提交时,它不会采用我定义的两个变量并使用它们。有什么想法吗?@benknighthorse:嗯,你没有问过提交表格的问题。当前,整个函数(
ds.route()
)设置为在表单提交时执行。如果您想在其他事件或代码中的其他时间执行它,只需在需要调用它的地方调用
ds.route()
函数。是否有一种方法可以链接整个代码,以便每个人都能更好地了解我的目的?@benknighthorse:我想您可以提供JSFIDLE链接或PasteBin链接。不过,最好只将其保存在相关代码中,或者保存在一个有点做作的示例中。仅仅发布一个完整的代码库通常是不受欢迎的,因为它充满了不相关的东西。目前,听起来好像您正在尝试手动调用
ds.route()
函数,您可以这样做。您所需要做的就是传入一个包含它所需的3个值的结构,并传入一个函数,以便它在完成时调用。我感谢您的帮助。我没有传递它需要的3个变量。我会试试看,然后回来汇报。