Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

javascript - How to pass objects in parameters in onclick() event?

I have this function:

function createMarkersForPlaces(places, infowindow) {
  for (var i = 0; i < places.length; i++) {
    var place = places[i];
    var marker = new google.maps.Marker({
      map: map,
      title: place.name,
      position: place.geometry.location,
      id: place.place_id,
      animation: google.maps.Animation.DROP
    });
    placeMarkers.push(marker);
    // if user clicks one of the marker, execute getPlaceDetails
    // for that specific place
    marker.addListener('click', function() {
      if (infowindow.marker == this) {
      } else {
        getPlacesDetails(this, infowindow);
      }
    });
    // based on the places above, populate list in html
    $("ul").append("<li><a href='#' onclick='getPlacesDetails(" + marker + "," + infowindow ")' class='w3-bar-item'>" + place.name + "</a></li>");
  }
}

but this line of code does not work.

$("ul").append("<li><a href='#' onclick='getPlacesDetails(" + marker + "," + infowindow ")' class='w3-bar-item'>" + place.name + "</a></li>");

inside of a function where marker and infowindow are defined, and other than this line of code, the function works perfect. Marker is an object from google.maps.marker, and infowindow is an object from google.maps.InfoWindow. How can I make it work?

function getPlacesDetails(marker, infowindow) {some function...}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

marker is an object, so you won't be able to convert it to a string to be put into the onclick attribute, and it's outside of the window scope, so you won't be able to do it directly in the onclick attribute anyways. I would probably do it like this:

var $li = $("<li><a href='#' class='w3-bar-item'>" + place.name + "</a></li>");
$("ul").append($li);
$li.on('click', getPlacesDetails.bind(this, marker, infowindow));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...