【问题标题】:Get specfic child, when click on map custom control单击地图自定义控件时获取特定的孩子
【发布时间】:2025-12-29 02:25:12
【问题描述】:

我有一个div 和它的三个span children,当我在clickdiv 时使用JQuery 然后使用下面的function 我能够识别出child 是@ 987654332@或clicked

$('.unitContainer').on('click','span',function(){
     $('.unitContainer').children('span').each(function () {
        $(this).css('color','white');
    });
    console.log($(this).text()); // "this" is the current element in the loop
    $(this).css('color','black'); // This line change attribute of targeted div
});

现在我想要这个事件,如果那个 div 将是 Map 上的自定义控件。

我试过了:

google.maps.event.addDomListener(unitControlDiv, 'click', function() {          
    $('.unitContainer').children('span').each(function () {
        $(this).css('color','white');
    });
    $(unitControlDiv).css('color','black');
});

还有这个:

 google.maps.event.addDomListener(unitControlDiv, 'click', function() {         
    $('.unitContainer').children('span').each(function () {
        $(this).css('color','white');
    });
    $(this).css('color','black');
});

但两者都不起作用。我现在怎么做才能让它发挥作用?

更新 1

1 : 默认控制 2:我的控件(自定义控件)(具有 3 个跨度的 Div)

更新 2

这个demo 使用JQuery 成为目标span

这个demo(地图上的div)没有工作。

【问题讨论】:

  • 对不起,'div 将自定义控件'是什么意思?
  • 我的意思是我在地图上添加了那个 div。 Google Map 提供的地图上有一些控件,如ZoomIn btnZoomOut Btn 'Round Navigator' taht。但是我手动添加了这个 div,所以我认为它是一个自定义控件。 (我想也许是错的)
  • @setec 我更新了图片也许现在会更清楚
  • 还更新了JSFiddle 两个案例的演示

标签: javascript jquery html google-maps-api-3 addeventlistener


【解决方案1】:

鼠标事件目标的一种可能解决方案:

google.maps.event.addDomListener(unitControlDiv, 'click', function(evt) {

    $('.unitContainer').children('span').each(function () {
        $(this).css('color', 'white');
    });

    //$(this).css('color', 'black');
    evt.target.setAttribute('style', 'color: black');
});

例如at jsfiddle

更新:属性的变化可以使用,例如:

var innerText = evt.target.innerText;
if (innerText == 'mi' || innerText == 'km' || innerText == 'ft') {
    evt.target.setAttribute('style', 'color: black');
}

Updated example.

【讨论】:

  • 这是一个不错的技巧,但当用户点击角落时也会出现问题:(
  • 嗯,太好了。我已经使用了这个技巧if(evt.target.getAttribute('style') === "color: white;") {。谢谢
【解决方案2】:

Here 它是如何工作的。

var milesSpan = $('<span class="custom-button" id="mi">mi</span>');
var kmSpan = $('<span class="custom-button" id="km">km</span>');
var feetSpan = $('<span class="custom-button" id="feet">ft</span>');

var hi = function() {
    alert($(this).attr('id') + " clicked!");
};
milesSpan.click(hi);
kmSpan.click(hi);
feetSpan.click(hi);

只需将“hi”替换为您的代码,“this”指的是 span 对象;

【讨论】:

  • 通过这样做我必须写三个不同的events?我希望像在 JQuery 中那样在单个事件中这样做
  • @BluAngel 是的,这有什么问题?您的代码不起作用,因为您甚至在将元素附加到文档之前就将事件间接绑定到元素。如果您像本示例中那样直接绑定事件,它将起作用。这意味着您必须将其绑定到每个按钮 3 次。
  • $('.unitContainer').on('click','span',function(){ $('.unitContainer').children('span').each(function () {}); });通过在其父级上应用所有三个跨度的单击事件?