MarkerWithLabel labelContent div onclick事件

时间:2016-01-18 17:15:33

标签: javascript css google-maps google-maps-api-3

我创建了一个包含多个DIV的标记,我希望能够访问单个DIV上的点击事件,而不仅仅是整个标记。

这是我的标记:

var marker = new MarkerWithLabel({
  position: myMap.getCenter(),
  map: myMap,
  opacity: 0.0,
  labelContent: "<div id=container>" +
  " <div id=largeDiv" +
  "></div>" +
  " <div id=smallDiv" +
  "></div>" +
  "</div>",
  labelAnchor: new google.maps.Point(width/2, height/2),
  labelClass: "labelClass" // the CSS class for the label
});

这是我尝试过的三种解决方案,以便在“largeDiv”上注册点击事件

$(document).ready(function() { // Works but too early, has no effect
  alert("Solution 1");
  $("#largeDiv").on("click", function() {
  alert("clicked largeDiv");
  });
});
$(document).on('DOMNodeInserted', function(e) { // Does not work
  if (e.target.id == "largeDiv") {
    alert("Solution 2");
    $("#largeDiv").on("click", function() {
      alert("clicked largeDiv");
    });
  }
});
setTimeout(function() { // Works
  alert("Solution 3");
  $("#largeDiv").on("click", function() {
      alert("clicked largeDiv");
  });
}, 1000);

第三个解决方案显然是一个糟糕的解决方案,我宁愿在创建DIV后立即添加点击监听器。我最好如何做到这一点?

CODEPEN

2 个答案:

答案 0 :(得分:1)

//it works

var div = document.createElement('div'),
    textElem = document.createTextNode('label');
div.appendChild(textElem);
$(div).on("click", function () {
  alert("click");
});

var marker = new MarkerWithLabel({
  position: myMap.getCenter(),
  map: myMap,
  opacity: 0.0,
  labelContent: div,
  labelAnchor: new google.maps.Point(width/2, height/2),
  labelClass: "labelClass" // the CSS class for the label
});

答案 1 :(得分:0)

在将div添加到标记之前将其创建为jQuery HTML元素。同时为其添加事件侦听器。例如我认为这应该有效:

var yourDiv = $("<div id=container>" +
  " <div id=largeDiv" +
  "></div>" +
  " <div id=smallDiv" +
  "></div>" +
  "</div>");

yourDiv.on("click", function() {
  alert("clicked largeDiv");
});

var marker = new MarkerWithLabel({
  position: myMap.getCenter(),
  map: myMap,
  opacity: 0.0,
  labelContent: yourDiv,
  labelAnchor: new google.maps.Point(width/2, height/2),
  labelClass: "labelClass" // the CSS class for the label
});