按钮而不是选择

时间:2012-05-28 16:50:57

标签: javascript google-maps select button input

我正在网站上工作,我想使用图标来选择旅行模式, 我有一个工作功能,但它只适用于选择输入。 有没有办法修改它以用于按钮?

提前致谢!

功能:

function calcRoute() {
  var selectedMode = document.getElementById("mode").value;
  var request = {
      origin: thuis,
      destination: kabk,
      // Note that Javascript allows us to access the constant
      // using square brackets and a string value as its
      // "property."
      travelMode: google.maps.TravelMode[selectedMode]
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });

HTML - 选择输入

<select id="mode" onchange="calcRoute();">
    <option value="DRIVING">Driving</option>
    <option value="WALKING">Walking</option>
</select>

HTML - 按钮输入(?)

<form id="mode">
    <input type="button" onchange="calcRoute();" value="DRIVING">
    <input type="button" onchange="calcRoute();" value="WALKING">
</form>

2 个答案:

答案 0 :(得分:1)

按钮没有onchange个事件。请改用onclick事件

<form id="mode">
    <input type="button" onclick="calcRoute(this);" value="DRIVING" />
    <input type="button" onclick="calcRoute(this);" value="WALKING" />
</form>

修改 您必须调整calcRoute功能

function calcRoute() {
   var selectedMode = document.getElementById("mode").value;
   //...

function calcRoute(btn) {
    var selectedMode = btn.value;
    // ...

答案 1 :(得分:0)

function calcRoute(ev) {
    var ev = ev || window.event,
        btn = (ev.target || ev.srcElement);
    var selectedMode = btn.value;  //"this" will return the element in the demo
    var request = {
        origin: thuis,


<form id="mode">
            <!--Use onClick-->
    <input type="button" onclick="calcRoute(ev);" value="DRIVING" />
    <input type="button" onclick="calcRoute(ev);" value="WALKING" />
</form>

This should work for you. :) 工作演示: http://jsfiddle.net/DerekL/T7NrF/