for (var p = 0; p < tokiyoPoints.length; p++) { //for loop
var tpoint = new google.maps.Marker({ //MAP MARKER
map: map, //MAP BY ID
//MARKER DROP
animation: google.maps.Animation.DROP,
venue: tokiyoPoints[p].pointId, //FOR LIKES AND RATING
title: tokiyoPoints[p].pointName, //TITLE OF POINT
show: ko.observable(true), //SHOW POINT
selected: ko.observable(false), //SELECT POINT
position: { //POINT POSITION
lat: tokiyoPoints[p].pointLat,
lng: tokiyoPoints[p].pointLng
}
});
tokiyo.push(tpoint); //ADD POINT AT THE END
tpoint.addListener('click', function() {
//CLICK ON THE POINTER
pointerInfo(this, tokyoInfo);
});
tpoint.addListener('click', function() {
//CLICK ON THE POINTER
BOUNCE(this);
});
tpoint.addListener('mouseover', function() {
//MOSEOVER ON POINT
this.setIcon(nIcon);
});
tpoint.addListener('mouseout', function() {
//MOUSEOUT FROM THE POINTER
this.setIcon(uIcon);
});
}
它给出了错误-
Dont make functions inside loop js
最佳答案
抛出错误的原因是您在循环中创建函数(事件处理程序)。
因此,如果您有 100 个点,您将创建 400 个函数,但它们的结构将保持不变。避免这种情况的正确方法是在循环外部有一个命名函数并将这些函数的引用传递给事件。
for (var p = 0; p < tokiyoPoints.length; p++) { //for loop
var tpoint = new google.maps.Marker({ //MAP MARKER
map: map, //MAP BY ID
//MARKER DROP
animation: google.maps.Animation.DROP,
venue: tokiyoPoints[p].pointId, //FOR LIKES AND RATING
title: tokiyoPoints[p].pointName, //TITLE OF POINT
show: ko.observable(true), //SHOW POINT
selected: ko.observable(false), //SELECT POINT
position: { //POINT POSITION
lat: tokiyoPoints[p].pointLat,
lng: tokiyoPoints[p].pointLng
}
});
tokiyo.push(tpoint); //ADD POINT AT THE END
tpoint.addListener('click', clickHandler1);
tpoint.addListener('click', clickHandler2);
tpoint.addListener('mouseover', mouseOverHandler);
tpoint.addListener('mouseout', mouseOutHandler);
}
function clickHandler1() {
//CLICK ON THE POINTER
pointerInfo(this, tokyoInfo);
}
function clickHandler2() {
//CLICK ON THE POINTER
BOUNCE(this);
}
function mouseOverHandler() {
//MOSEOVER ON POINT
this.setIcon(nIcon);
}
function mouseOutHandler() {
//MOUSEOUT FROM THE POINTER
this.setIcon(uIcon);
}
关于javascript - 不要在循环内创建函数 jshint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43972641/