以对象为引号的onclick事件

时间:2018-07-05 20:48:26

标签: javascript google-maps javascript-events

使用Google Maps和Places API,我正在为由功能 generateInfoWindow(location)生成的每个标记呈现信息窗口。

在其中创建一个字符串 HTML ,该字符串将传递到google maps markers内容属性。

功能

function generateInfoWindow(location) {
  var html = "<div class = 'infowindowContainer'>" +
    "<span class = 'infoWindowHeader'>" + location.name + "</span>" +
    "<div class = 'row'>" +
    "<span class = 'col-xs-12'> ... : " + getInfoWindowDetails(location).adress + "</span>" +
    "<span class = 'col-xs-12'> ... : " + getInfoWindowDetails(location).open_hours + "</span>";

  if (location.offers.length > 0) {
    html +=
      "<span class = 'col-xs-12 iwOffers'> ... </span>" +
      "</div>" + //ends row
      "<div class = 'infoWindowCircleContainer'>";
    for (var i = 0; i < location.offers.length; i++) {
      html += "<span class = 'infoWindowCircle'>" + location.offers[i].offer_text + "</span>";
    }
    html += "</div>" //CircleContainer
  }

  html += "<span class = 'showMore' onclick = 'processWin(" + location + ")'>Show more</span>";
  html += "</div>"; //InfoWindowContainer the parent to all

  return html;
}

function processWin(location) {
  var winMarker;
  var winnerMap;
  var mapOptions = {
    zoom: 15,
    center: location.geometry.location,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    styles: googleMapsStyles
  };

  var locationId = location.place_id;
  var request = {
    placeId: locationId
  };

  places.getDetails(request, getWinnerDetails); //Where getWinnerDetails is the callback

  //since the location that we are passing in the callback function is the one we get as a json from the detailed search we are gonna have to use our modified vars associated with the location here such as .keyword
  $("#foodType").text("Typ av mat : " + location.keyword);
  winnerMap = new google.maps.Map(document.getElementById('displayWinnerMap'), mapOptions);

  for (var i = 0; i < markers.length; i++) {
    if (markers[i].placeId == location.place_id) {
      winMarker = markers[i];
      break;
    }
  }

  //setOfferCircles(location);
  winMarker.setMap(winnerMap);
  $("#displayWinPage").css("display", "block");
  doScroll("#displayWinPage");
}

我在其中将跨度附加到showMore类的地方,我希望附加一个onclick事件,该事件将调用方法 processWin(location),在此我传递location变量。 (将是多个标记)。

我似乎无法在onclick事件中传递对象位置,并且 我不明白为什么。请赐教。

1 个答案:

答案 0 :(得分:0)

转换为字符串的对象将成为[对象对象],这就是您作为参数传递的内容,而不是对象本身。这是显示错误输出的示例代码

imshow("Display window", image*10);

使用JSON.stringify(location)可以正确获取对象输出,如下所示。

var location = {x : 100, y : 100};
var html = "<span class = 'showMore' onclick = 'processWin(" + location + ")'>Show more</span>";
console.log(html);

Output: <span class = 'showMore' onclick = 'processWin([object Object])'>Show more</span>