var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
// and store them in funcs
funcs[i] = function() {
// each should log its value.
console.log("My value: " + i);
};
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}
Run Code Online (Sandbox Code Playgroud)
它输出这个:
我的价值:3
我的价值:3
我的价值:3
而我希望它输出:
我的价值:0
我的价值:1
我的价值:2
使用事件侦听器导致运行函数的延迟时,会出现同样的问题:
var buttons = document.getElementsByTagName("button");
// let's create 3 …
Run Code Online (Sandbox Code Playgroud)我一直在玩Google的DistanceMatrixService.下面的代码可行,但是,如何将另一个参数传递给回调函数或从回调中获取其中一个值?
例如:我有两个div想要在(Results1和Results2)中显示不同的结果,所以我想我需要
将另一个值传递给GoogleMapDistance函数,如GoogleMapDistance(YourLatLong,DestLatLong,TheDiv)
或者
能够抓取ResultStr位于回调文档外部.getElementById ("Results1").innerHTML = ResultStr;
或者
将innerHTM设置为函数document.getElementById("Results1")的返回值.innerHTML = GoogleMapDistance(YourLatLong,DestLatLong);
我被卡住了.我怎么能做到这一点?它现在的样子是我只能运行所有这些代码并且只能写入一个div.
<div id="Results1"></div>
<div id="Results2"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function GoogleMapDistance(YourLatLong,DestLatLong)
{
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [YourLatLong],
destinations: [DestLatLong],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status)
{
if (status == google.maps.DistanceMatrixStatus.OK)
{
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++)
{
var results = response.rows[i].elements;
for …
Run Code Online (Sandbox Code Playgroud)