自定义控件不响应jQuery调用在谷歌地图Api



你能看看下面的代码,让我知道为什么我不能推谷歌地图自定义控件调用jquery .click()函数?下面是创建映射元素并分配类(.test)

的部分
var controlDiv = document.createElement('div');
var controlButton = document.createElement('button');
controlButton.setAttribute("class", "btn btn-mini btn-success test");
controlButton.innerHTML = 'Control Button';
controlDiv.appendChild(controlButton);
// Add 'div' containing button to the map
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
$('.test').click(function () {
    alert("Handler for");
});

我已经测试了代码,它的工作在地图UI,但不是在地图自定义控件格式!

如果你等到地图空闲(完成渲染),那么按钮是DOM的一部分,jquery选择器工作:

var controlDiv = document.createElement('div');
var controlButton = document.createElement('button');
controlButton.setAttribute("class", "btn btn-mini btn-success test");
controlButton.innerHTML = 'Control Button';
controlDiv.appendChild(controlButton);
// Add 'div' containing button to the map
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
google.maps.event.addListenerOnce(map, 'idle', function() {$('.test').click(function () {
      alert("Handler for");
    });
});
工作示例

我推荐事件委托。它使这类问题变得简单。您不仅可以将它用于Maps API问题,还可以用于任何需要响应尚未创建的DOM元素上的事件的情况,例如用Ajax调用加载的内容。

让我假设你的地图容器<div>idmap_div

然后,这里有这样的代码:

$('.test').click(function () {
    alert("Handler for");
});

改为:

$('#map_div').on( 'click', '.test', function () {
    alert("Handler for");
});

这是如何工作的:而不是将事件处理程序附加到尚未创建的.test元素,它附加到映射容器,它应该已经存在,但事件处理程序函数仍然只响应点击你的.test元素一旦它被创建。

上面的代码适用于jQuery 1.7+。对于1.4.2+,它将是:

$('#map_div').delegate( '.test', 'click', function () {
    alert("Handler for");
});

最新更新