如何打印从函数返回的变量

How can I print a variable returned from a function?

本文关键字:函数 返回 变量 何打印 打印      更新时间:2023-09-26

我有这个功能:

function findAddressViaGoogle(address){
     var geocoder = new google.maps.Geocoder();
     geocoder.geocode( { 'address': address }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            return results[0].formatted_address;
        } else {
            console.log("Unable to find address: " + status);
        }
     });
}

如何打印此函数的返回值?

如果我这样做:

$('#location-suggest').text('Do you mean <a>'+findAddressViaGoogle($(this).val())+'</a> ?');

它打印未定义

回调是在Geocoder()内部的某个地方调用的,并且在findAddressViaGoogle()函数中未收到其返回值。

您可以初始化变量并将值传递给它:

function findAddressViaGoogle(address){
  var address = "";
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': address }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      address = results[0].formatted_address;
    } else {
      console.log("Unable to find address: " + status);
    }
  });
  return address;
}
var myAddress = findAddressViaGoogle('foobar');
alert(myAddress);

另外,请记住,必须先调用函数,然后它才能返回任何内容。

因此,要传递收集的值:

$('#myElementID').html(findAddressViaGoogle('foobar'));

你在寻找document.write吗?

像这样:

$(".putYourSelectorHere").html(findAddressViaGoogle())

.putYourSelectorHere替换为您的选择器(例如#output)。如果要在正文中使用body选择器打印结果:

$("body").html(findAddressViaGoogle())

http://api.jquery.com/html/