Bootstrap模态框每打开一次后续触发次数逐次累加问题排查
问题原因
你每次点击地图标记触发markers的click事件时,都会给#myModal新增一个show.bs.modal事件监听器,旧的监听器不会自动移除。点击多少次标记,就会绑定多少个相同的事件监听器,后续模态框触发show事件时所有绑定的监听器会依次执行,就出现了重复运行的问题。
修复方案
方案1:绑定前移除旧监听器(最便捷,无需大幅调整代码)
每次绑定新的show.bs.modal监听器前,先调用off移除同事件类型的旧监听器即可,修改后代码如下:
markers.on('click', function (e) { city = e.layer.options.title // 先移除之前绑定的show.bs.modal监听器,再绑定新的 $('#myModal').off('show.bs.modal').on('show.bs.modal', function (event) { var modal = $(this); $.when(runAjax('City Reference', 'source/php/getCityInfo.php', 'POST',city)) .then(function() { cityReference = ajaxResponse.place_id; $.when(runAjax('Photo Reference', 'source/php/getPhotoRef.php', 'GET', cityReference)) .then(function() { photoReference = ajaxResponse.photoR; modal.find('.modal-body').html('<img src=https://maps.googleapis.com/maps/api/place/photo?photoreference=' + photoReference + '&input=green%20lanes&sensor=false&types=(regions)&key=<<<HIDDEN>>>&maxwidth=400&maxheight=400></div>'); }); }); modal.find('.modal-title').html('<b>' + city + '</b>'); }) $('#myModal').modal('show'); });
方案2:将事件绑定移到点击逻辑外(更规范的写法)
避免重复绑定的最优做法是只绑定一次事件监听器,需要传递的城市参数通过模态框的data属性存储:
// 页面初始化时仅绑定一次show.bs.modal监听器 $('#myModal').on('show.bs.modal', function (event) { var modal = $(this); // 从模态框的data属性中取当前选中的城市名 var city = modal.data('selectedCity'); $.when(runAjax('City Reference', 'source/php/getCityInfo.php', 'POST',city)) .then(function() { cityReference = ajaxResponse.place_id; $.when(runAjax('Photo Reference', 'source/php/getPhotoRef.php', 'GET', cityReference)) .then(function() { photoReference = ajaxResponse.photoR; modal.find('.modal-body').html('<img src=https://maps.googleapis.com/maps/api/place/photo?photoreference=' + photoReference + '&input=green%20lanes&sensor=false&types=(regions)&key=<<<HIDDEN>>>&maxwidth=400&maxheight=400></div>'); }); }); modal.find('.modal-title').html('<b>' + city + '</b>'); }) // 标记点击事件仅负责传递参数、打开模态框 markers.on('click', function (e) { const city = e.layer.options.title; // 把选中的城市存入模态框的data属性 $('#myModal').data('selectedCity', city).modal('show'); });
内容的提问来源于stack exchange,提问作者SynDuck
相关产品推荐
相关产品推荐

