如何在onclick()事件中的参数中传递对象? [英] How to pass objects in parameters in onclick() event?

查看:33
本文介绍了如何在onclick()事件中的参数中传递对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能:

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>");

在定义了标记和信息窗口的函数内部,并且除了此代码行之外,该函数都可以完美地工作.标记是来自google.maps.marker的对象,而信息窗口是来自google.maps.InfoWindow的对象.我该如何运作?

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...}

推荐答案

marker 是一个对象,因此您将无法将其转换为要放入的字符串onclick 属性,并且它不在窗口范围之内,因此无论如何您将无法直接在 onclick 属性中进行操作.我可能会这样:

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));

这篇关于如何在onclick()事件中的参数中传递对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆