Javascript 如何在onclick()事件中传递参数中的对象?
我有这个功能:Javascript 如何在onclick()事件中传递参数中的对象?,javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,我有这个功能: 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.
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>");
}
}
首先,您的连接是错误的。您需要通过终止字符串、连接变量,然后添加另一个字符串,将变量连接到字符串中。不要忘记每次连接之间的
+
:
onclick='getPlacesDetails("' + marker + '","' + infowindow + '")'
其次,所有这一切都将把整个对象连接到字符串中,而不是该对象的一些实际可用的字符串属性
现在,不应该将内联HTML事件属性用于事件绑定。100年前我们就是这样做的,现在有人不这么做了。相反,在脚本中执行所有事件绑定。这也将允许您完全避免连接
最后,如果你没有在任何地方导航,不要使用超链接。这在语义上是不正确的,您必须禁用链接的本机单击行为,更不用说它会导致浏览器历史记录出现问题。几乎可以单击任何可见元素,因此只需将单击
绑定到li
并完全忘记a
:
var li = document.createElement("li"); // Create the element in memory
li.classList.add("w3-bar-item"); // Configure the CSS
// Set up the click event to an anonymous function that calls the
// actual function you want and passes the parameters it needs:
li.addEventListener("click", function(){
getPlacesDetails(marker, infowindow)
});
marker
是一个对象,因此您无法将其转换为字符串以放入onclick
属性,并且它不在窗口范围内,因此您无论如何也无法直接在onclick
属性中执行。我可能会这样做:
var $li = $("<li><a href='#' class='w3-bar-item'>" + place.name + "</a></li>");
$("ul").append($li);
$li.on('click', getPlacesDetails.bind(this, marker, infowindow));
var$li=$(“”);
$(“ul”)。追加($li);
$li.on('click',getPlacesDetails.bind(this,marker,infowindow));
非常感谢您的回答!但它不能正确地传递对象。@NicholasHuh请参阅更新的答案以了解更现代的方法。
var li = document.createElement("li"); // Create the element in memory
li.classList.add("w3-bar-item"); // Configure the CSS
// Set up the click event to an anonymous function that calls the
// actual function you want and passes the parameters it needs:
li.addEventListener("click", function(){
getPlacesDetails(marker, infowindow)
});
var $li = $("<li><a href='#' class='w3-bar-item'>" + place.name + "</a></li>");
$("ul").append($li);
$li.on('click', getPlacesDetails.bind(this, marker, infowindow));