如何在谷歌地图监听器中使用布尔值
How to use bool in Google maps listener?
我在这个问题上停了 4 小时,if
在调用谷歌地图事件时忽略了我的布尔值。我需要在参数中提供不同的数据。也许世界上有人知道为什么?
console.log
同时点击后抛出:
true before click
stack.html:56[object HTMLDivElement]in listener
stack.html:62[object HTMLDivElement]bunga bunga
破碎的布尔值:
this.b = true;
...
console.log(this.b + " beafore click");
this.mapListener = google.maps.event.addListener(map, 'click', function(e) {
console.log(this.b + "in listener");
if (this.b==true) {
console.log(this.b + "true works");
tools[type](e.latLng, last_marker_origin);
this.b = false;
} else {
console.log(this.b + "bunga bunga");
//tools[type](e.latLng);
}
});
this
引用我的对象默认值设置为 false 中的"属性",但当我更改选项时,它被标记为 true。
我现在去睡觉了。我会在早上回答。
您的问题是this
不再是对您的properties
的有效引用。处理特定问题的最简单方法是更改代码:
this.b = true;
var props = this;
console.log(this.b + " beafore click"); //Notice that "this" is still valid here
this.mapListener = google.maps.event.addListener(map, 'click', function(e) {
console.log(props.b + "in listener");
if (props.b == true) {
console.log(props.b + "true works");
tools[type](e.latLng, last_marker_origin);
props.b = false;
} else {
console.log(props.b + "bunga bunga");
//tools[type](e.latLng);
}
});
根本问题是实际调用回调函数的代码位于完全不同的范围内,因此当代码运行时,this
的含义已更改。设置引用并将其放入代码中将解决您的问题。
这里的问题是this
的范围。当您在单击事件处理程序函数中时this
不再引用属性对象,而是引用事件处理程序。事件处理程序是所谓的闭包。
对于您的问题,有两种可能的解决方案。
-
使用局部变量(
var b
而不是this.b
)作为你的值,局部变量被复制到闭包中,因此该值可以在闭包内外使用:var b = true; console.log(b + " beafore click"); this.mapListener = google.maps.event.addListener(map, 'click', function(e) { console.log(b + "in listener"); if (b==true) { console.log(b + "true works"); tools[type](e.latLng, last_marker_origin); b = false; } else { console.log(b + "bunga bunga"); //tools[type](e.latLng); } });
-
将
this
保存在局部变量中,这是避免作用域问题的非常常见的技术://save this in a locale variable, now 'me' provides access to this scope var me = this; me.b = true; console.log(me.b + " beafore click"); this.mapListener = google.maps.event.addListener(map, 'click', function(e) { console.log(me.b + "in listener"); if (me.b==true) { console.log(me.b + "true works"); tools[type](e.latLng, last_marker_origin); me.b = false; } else { console.log(me.b + "bunga bunga"); //tools[type](e.latLng); } });
相关文章:
- 如何从javascript/jquery中的复选框中获取布尔值
- KendoUI网格行过滤器,带有布尔值下拉列表
- php布尔值's小写AND大写和数字布尔值'可以接受
- select中布尔值的Angularjs ng值不起作用
- 由于布尔值的变化,Django视图中的字符串格式不正确
- MeteorJs Alded autoform,如何从布尔值复选框中获得所需值
- 将字符串动态转换为布尔值
- 将布尔值存储在隐藏字段中以进行表单处理
- 类型错误:布尔值不是 Angular 中登录函数的函数
- Yui Get 复选框返回数组而不是布尔值
- 为什么 1.2 == true 返回 false 如果布尔值 (1.2) 实际上是真的
- 为什么第一个将其视为布尔值,其次不将其视为布尔值
- 当值可能不是正确的布尔值时,如何测试 true
- jquery -ajax 不检查控制器的布尔值
- JS生成随机布尔值
- 使用Angular更改JSON中存储的布尔值
- 如何检查类型是否为布尔值
- 在EaselJS中,如果鼠标按下,我如何获得布尔值
- typescript中的嵌套布尔值
- 如何在谷歌地图监听器中使用布尔值