给百度地图覆盖物添加事件处理函数传参数

给事件处理函数传参数

今天刷百度前端学院的任务,遇到了一个问题,需要给事件处理函数传参数;我把问题抽象成下面问题:

var lis = document.getElementsByTagName('li');
for(var i=0; i<lis.length; i++){ this.i=i; btn.addEventListener('click',handler.bind(this)); } //我想在事件处理函数里面获得i。 function handler(e){ this.i; }

ES5中bind()解决:

解决方法,将事件处理函数的上下文绑定到for循环里面的this;事件处理函数的上下文不在是btn对象;

分析一下原理,首先详细研究一下bind函数; 
bind函数用于将当前函数和指定对象绑定,返回一个新的函数,当新函数被调用时,代码会在指定对象的上下文中执行。 
语法为:

bar.bind(上下文参数, 普通参数1, 普通参数2, …);普通参数将传入bar函数          

详细:https://blog.csdn.net/github_38861674/article/details/72625542

转载于:https://www.cnblogs.com/gavin1024/p/9683288.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
百度地图添加复杂覆盖物的步骤包括以下几个部分: 1. 引入百度地图 JavaScript API,并在 Vue 组件中加载地图。 2. 定义复杂覆盖物的构造函数,包括需要的参和方法。 3. 在 Vue 组件中创建复杂覆盖物对象,并添加地图中。 下面是一个简单的示例代码,可以帮助您理解如何在 Vue 中添加复杂覆盖物: ``` <template> <div class="map-container"> <div class="map" ref="map"></div> </div> </template> <script> export default { name: 'MapContainer', data() { return { map: null, complexOverlay: null }; }, mounted() { // 加载地图 this.initMap(); }, methods: { initMap() { this.map = new BMap.Map(this.$refs.map); this.map.centerAndZoom(new BMap.Point(116.404, 39.915), 11); // 创建复杂覆盖物 this.createComplexOverlay(); // 添加复杂覆盖物地图中 this.map.addOverlay(this.complexOverlay); }, createComplexOverlay() { function ComplexOverlay(point, text) { this._point = point; this._text = text; } ComplexOverlay.prototype = new BMap.Overlay(); ComplexOverlay.prototype.initialize = function(map) { this._map = map; var div = document.createElement('div'); div.style.position = 'absolute'; div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat); div.style.backgroundColor = 'red'; div.style.color = 'white'; div.style.padding = '5px'; div.style.borderRadius = '5px'; div.innerText = this._text; map.getPanes().labelPane.appendChild(div); this._div = div; return div; }; ComplexOverlay.prototype.draw = function() { var pixel = this._map.pointToOverlayPixel(this._point); this._div.style.left = pixel.x + 'px'; this._div.style.top = pixel.y + 'px'; }; var point = new BMap.Point(116.404, 39.915); var text = '这是一个复杂的覆盖物'; this.complexOverlay = new ComplexOverlay(point, text); } } }; </script> <style scoped> .map-container { width: 100%; height: 100vh; } .map { width: 100%; height: 100%; } </style> ``` 在这个示例代码中,我们首先在 Vue 组件中加载了百度地图,并创建了一个 `MapContainer` 组件。在 `initMap()` 方法中,我们创建了一个复杂覆盖物对象,并在地图添加了这个覆盖物。 复杂覆盖物是通过定义一个构造函数来创建的,并继承了 `BMap.Overlay` 类的原型。这个构造函数包括一个表示位置的坐标点和一个文本字符串。在 `initialize()` 方法中,我们创建了一个 DOM 元素,并设置了样式和文本内容。然后,我们将这个 DOM 元素添加地图的 `labelPane` 图层上,最后将这个 DOM 元素返回,以便在地图上显示。在 `draw()` 方法中,我们更新了 DOM 元素的位置,以确保它始终位于正确的位置。 这只是一个简单的示例,您可以根据您的需求来定义更复杂的覆盖物,并实现更多的方法和属性。希望这能帮到您。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值