简体   繁体   English

Google Maps Popover点击事件会多次触发

[英]Google Maps Popover click event fires multiple times

I have a google map with markers. 我有一个带标记的谷歌地图。 Each marker when clicked, shows an infowindow. 单击时,每个标记显示一个信息窗口。 Inside the infowindow is a button to add some data to a queue. 在infowindow内部是一个向队列添加一些数据的按钮。 on the first click of an add to queue button, it fires once, click a second button it fires twice, click a third and it fires three times and so on. 在第一次单击添加到队列按钮时,它会触发一次,单击第二个按钮,它会触发两次,单击第三个按钮会触发三次,依此类推。

google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
        $('.show-compare').popover('destroy');
        infowindow.setContent('<div class="add-wrapper"><div class="show-compare" data-toggle="popover" data-placement="top" data-content="Add to compare basket">CLICK ME</div></div>);
        infowindow.setOptions({maxWidth: 200});
        infowindow.open(map, marker);

        $('body').on("click", '.show-compare', function(e) {
                e.preventDefault();
                alert();//this fires x times, only should fire once per click!!

        }
    }) (marker, i));
}

HELP! 救命! Thank you :) 谢谢 :)

If the button that is being clicked is inside the marker the click event could be propagating up to the marker, which then adds another click event to the button. 如果正在单击的按钮位于标记内,则单击事件可能会传播到标记,然后标记会向该按钮添加另一个单击事件。 Hence the 1x, 2x, 3x, 4x firing pattern. 因此1x,2x,3x,4x发射模式。

Try adding a stop propagation function. 尝试添加停止传播功能。

$('body').on("click", '.show-compare', function(e) {
    e.preventDefault();
    e.stopPropagation();
    alert();
}

What your code do is: every time there is a click event on the marker, your code will register another click event handler on the body tag. 您的代码所做的是:每次标记上都有单击事件时,您的代码将在body标记上注册另一个单击事件处理程序。 You should move it out side the 你应该把它移出去

google.maps.event.addListener(marker, 'click', (function(marker, i)

That way you register only one click handler on body tag 这样,您只能在body标签上注册一个点击处理程序

$('body').off("click", '.show-compare').one("click", '.show-compare', function(e) {
    e.preventDefault();
    e.stopPropagation();
    alert();
}

This worked for me 这对我有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM