Javascript jQuery更改后未定义变量
Javascript jQuery更改后未定义变量,javascript,jquery,google-maps-api-3,Javascript,Jquery,Google Maps Api 3,circle是在jQuery('#area').change()外部定义的,但是当我试图从jQuery('#area').change()函数内部访问它时,我得到一个未定义的错误。为什么会这样?在.change函数中,更改此行: var circle = new google.maps.Circle({ center: latLng, radius: radius, strokeColor: "#FF0000", strokeOpacity: 0.5, s
circle
是在jQuery('#area').change()外部定义的,但是当我试图从jQuery('#area').change()函数内部访问它时,我得到一个未定义的错误。为什么会这样?在.change函数中,更改此行:
var circle = new google.maps.Circle({
center: latLng,
radius: radius,
strokeColor: "#FF0000",
strokeOpacity: 0.5,
strokeWeight: 1,
fillColor: "#FF0000",
fillOpacity: 0.2
});
circle.setMap(map);
map.fitBounds(circle.getBounds());
jQuery('#area').change(function() {
radius = jQuery('#area').val();
var newLatLng = marker.getPosition();
circle.setMap(null);
var circle = new google.maps.Circle({
center: latLng,
radius: radius,
strokeColor: "#FF0000",
strokeOpacity: 0.5,
strokeWeight: 1,
fillColor: "#FF0000",
fillOpacity: 0.2
});
circle.setMap(map);
map.fitBounds(circle.getBounds());
});
为此:
var circle = new google.maps.Circle({
按照您的方式,您正在创建一个名为circle
的新局部变量并设置其值,而不是设置circle
的全局定义的值。然后,当你下次来调用全局的circle.setMap(null)
时,它仍然是null
因此,如果您只想对圆的全局定义进行操作,请删除.change()
函数中的var
。如果您打算创建一个新的临时圆圈对象,仅在执行该函数后无法继续使用的.change()
函数期间使用,则将该本地副本命名为除圆圈
之外的其他对象。更改函数,更改此行:
var circle = new google.maps.Circle({
center: latLng,
radius: radius,
strokeColor: "#FF0000",
strokeOpacity: 0.5,
strokeWeight: 1,
fillColor: "#FF0000",
fillOpacity: 0.2
});
circle.setMap(map);
map.fitBounds(circle.getBounds());
jQuery('#area').change(function() {
radius = jQuery('#area').val();
var newLatLng = marker.getPosition();
circle.setMap(null);
var circle = new google.maps.Circle({
center: latLng,
radius: radius,
strokeColor: "#FF0000",
strokeOpacity: 0.5,
strokeWeight: 1,
fillColor: "#FF0000",
fillOpacity: 0.2
});
circle.setMap(map);
map.fitBounds(circle.getBounds());
});
为此:
var circle = new google.maps.Circle({
按照您的方式,您正在创建一个名为circle
的新局部变量并设置其值,而不是设置circle
的全局定义的值。然后,当你下次来调用全局的circle.setMap(null)
时,它仍然是null
因此,如果您只想对圆的全局定义进行操作,请删除.change()
函数中的var
。如果您打算创建一个新的临时圆圈对象,仅在执行该函数后无法继续使用的.change()
函数期间使用,则将该本地副本命名为圆圈
,因为您的内部函数包含var circle
。由于一种称为“var提升”的现象,整个函数将circle
视为局部变量,即使var语句稍后出现
将内部函数的循环命名为其他名称。因为内部函数包含var循环
。由于一种称为“var提升”的现象,整个函数将circle
视为局部变量,即使var语句稍后出现
将你的内部函数的圆命名为其他名称。同意jimbojw的观点这里有一把小提琴,它演示了:+1个很好的答案。解释器将一个范围内的所有变量声明视为该范围内的第一行。解释器将范围内的所有变量声明视为该范围内的第一行。