使用 addEventListener 处理 jQuery 单击 Google 地图信息窗口中 jQuery UI 地图选择器上的事件

Using addEventListener To Handle jQuery Click Events On Selectors Inside Google Maps infoWindow With jQuery UI Maps

问题:当试图在 Google 地图信息窗口中的选择器上触发 jQuery 事件时,捕获 gmap 对象中的事件所需的点击事件侦听器必须是其他点击功能的父级,导致第一次点击时无法触发点击事件。

我在 Whosebug 上找到的所有解决方案都展示了如何添加 eventListener,但仍然没有解决首次点击时无法触发的问题。

如果您使用 jQuery UI 地图来填充可打开 infoWindows 的可点击标记,并且希望能够针对 jQuery 的 infoWindow 内的元素,则以下解决方案将起作用您的主页(父)页面上的活动。

此解决方案解决了嵌套点击函数导致的典型首次触发问题,其中 jQuery 事件不会在第一次点击时触发,因为您的函数必须在 $('map_canvas' 的 addEventListener 中.gmap() 以便被捕获 - 但是,当然,它们将嵌套在另一个点击函数中,因此在第二次点击之前不会触发。

肯定有更多标准的 and/or eloquent 方法可以实现这一点,但除了需要稍微不典型的语法外,这解决了所有问题并提供了一个非常快速、直接、可行的解决方案对于一个非常令人沮丧的问题,为您节省了 8 个多小时的墙头抨击,我花了它来制作。

解决方案:

使用 $('#map_canvas').gmap() 上的点击事件侦听器作为万能的,具有允许我们确定 class 名称(s ),然后使用 if 语句查看它是否与我们希望在 infoWindow 中使用的任何 'selectors' 相匹配,并从那里开始执行常规功能。

为方便起见,jQuery(element) 被指定为等同于正常的 jQuery(this)

类 被拆分成一个数组,以说明单击对象上的多个 classes。

然后我们只使用 if 语句来检查我们希望用作选择器的 class 是否在被单击对象的 class 名称数组中,如果是的话, 放入我们通常的 jQuery 否则我们会为选择器放入一个嵌套的点击函数,在必要时简单地用 (element) 代替 (this)。

这可以很容易地调整为使用 id 作为选择器而不是 classes - 只需将 $(element).attr('class') 更改为 $(element).attr('id')

示例代码如下:

jQuery('#map_canvas').gmap().addEventListener('click', function(mainevent) {

    // We cannot directly target elements inside the Google map and infoWindows with jQuery, so here we catch all clicks on the map and then use if statements to see if the clicked element matches any of the selectors we wish to use.

    var element = jQuery(mainevent.target);
    if ( $(element).attr('class') ) { var MainEventClassList = $(element).attr('class').split(' '); }

    // Gets the classes of the clicked element into an array, so we can check for matches with if statements, as an equivalent to typical jQuery class selectors.  We have also made (element) available as a replacement for (this).



    if ( jQuery.inArray( 'SelectorClassName', MainEventClassList ) >= 0 ) {

        mainevent.preventDefault();
        mainevent.stopPropagation();
        var destinationid = jQuery(element).attr('href');
        alert(destinationid);

    }


});