无法使用javascript在隐藏字段中显示值?

时间:2018-06-28 03:41:14

标签: javascript php jquery asp.net google-maps-api-3

function show(a,b) {
    var origin = document.getElementById('Subadd').value;
    var destination = a.value;
    var service = new google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
        {
          origins: [origin],
          destinations: [destination],
          travelMode: google.maps.TravelMode.DRIVING,
          unitSystem: google.maps.UnitSystem.METRIC,
          avoidHighways: false,
          avoidTolls: false
        }, calcD);
}

function calcD(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
        alert('Error was: ' + status);
    } else {
        var origins = response.originAddresses;
        var destinations = response.destinationAddresses;
        for (var i = 0; i < origins.length; i++) {
          var results = response.rows[i].elements;
          for (var j = 0; j < results.length; j++) {
              c= results[j].distance.text;
              b.value=c;
          }
        }
    }
}

这里a和b是两个文本字段ID。从文本字段1 onchange中,函数show()将起作用,并在CalcD()函数中警告c的值。但是我无法将c的值传递给ID为b的文本字段。

1 个答案:

答案 0 :(得分:1)

之所以发生,是因为在函数CalcD中未定义b。您必须将其传递给函数或使用诸如document.getElementById之类的方法直接调用它。 然后您的代码必须是这样的:

function show(a,b) {
    var origin = document.getElementById('Subadd').value;
    var destination = a.value;
    var service = new google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
        {
          origins: [origin],
          destinations: [destination],
          travelMode: google.maps.TravelMode.DRIVING,
          unitSystem: google.maps.UnitSystem.METRIC,
          avoidHighways: false,
          avoidTolls: false
        }, calcD);
}

function calcD(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
        alert('Error was: ' + status);
    } else {
        var origins = response.originAddresses;
        var destinations = response.destinationAddresses;
        for (var i = 0; i < origins.length; i++) {
          var results = response.rows[i].elements;
          for (var j = 0; j < results.length; j++) {
              c= results[j].distance.text;
              b = document.getElementById('id of b input');
              b.value=c;
          }
        }
    }
}