jQuery .each循环 - 内部调用函数

时间:2015-03-09 18:33:47

标签: javascript jquery function each

如何在jQuery .each中调用函数?

目前我的功能仅在最后一次执行。

如何在每次调用函数MyCurrentPosition(dsRow)时编辑它以执行此操作?

这是代码:

Maps.GetCoordinates = function (jsonResponse) {

jQuery.each(jsonResponse, function(filterName,result) {

    var risultati = result;
    var items = risultati.rows;
    //console.log (risultati.total);

        if(risultati.total > 0)
        {
            jQuery.each(items, function(i,dsRow) {

                var myhtml= dsRow.latitude;

                //This work all time
                jQuery('#show_distance_'+dsRow.id).html(myhtml).show();

                //but this function only last time print result 
                MyCurrentPosition(dsRow);
            });
        }
    }); //end foreach
}

编辑:这是MyCurrentPosition函数:

var options = { enableHighAccuracy: true, timeout: 12000, maximumAge: 0 };
function MyCurrentPosition(dsRow) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (pos) {
            crd = pos.coords;
            HelloMapsSearch.GetDistance(crd,dsRow);
        }, 
    showError, 
    options );
    } else {
        alert("Geolocation is not supported by your device.");
    }
    //return crd;

}

HelloMapsSearch.GetDistance = function (crd,dsRow) {
    var origine = crd;
    var destinazione = dsRow;
    var mxstart = new google.maps.LatLng(origine.latitude,origine.longitude);
    var mxend = new google.maps.LatLng(destinazione.latitude, destinazione.longitude);
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
    {
      origins: [mxstart],
      destinations: [mxend],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    //}, callback );
      }, function(response, status) {callback(response, status, dsRow)});
}

function callback(response, status, dsRow) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    var outputDiv = document.getElementById('show_distance_'+dsRow.id);
    outputDiv.innerHTML = '';
    for (var i = 0; i < origins.length; i++) {
        var results = response.rows[i].elements;
        for (var j = 0; j < results.length; j++) {

            outputDiv.innerHTML += "Origine:"+origins[i] + '<br> to  destinazione:' + destinations[j] + '<br>'
            + ': ' + results[j].distance.text + ' in '
            + results[j].duration.text + '<br>';     
        }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

要检查的一些事情。 jsonResponse必须是数组。 risultati还必须包含Array类型的行。

对于名为MyCurrentPosition的内部函数,我们目前缺少实现本身。

内部是否有if阻止日志记录?请分享代码。