简体   繁体   中英

Problem to display to execute a function when clicking on a button inside a leaflet popup

I'm struggling with a simple issue in JS. I have a Leaflet map with a bunch of markers, when clicking on a marker you have a popup with some info and two buttons. I try to display a div with more info when the button is clicked. It seems that when i click on it, the div is displayed and all the other one as well. The condition seems true for all the marker in the loop which is not correct as only one button is clicked.

Do you guys have any idea ?

 $.getJSON(uri, function(data){ for (let river in data.rivers){ var popup = data.rivers[river].name + '<br/><b>Water Level :</b> ' + data.rivers[river]['water-level'] + " m3/s" + '<br/><b>Water Temperature :</b> ' + data.rivers[river]['temperature'] + " °C" + '<br/><b>Sample Time :</b> ' + data.rivers[river]['date-and-time'] + '<button type="button" id="more-infos" class="btn btn-primary">More infos</button>' + " " + '<button type="button" class="btn btn-warning">Alert me</button>'; // The problem is here $("div").on('click', '#more-infos', function (e) { onClickMoreDetails(data.rivers[river]); }); var marker = new L.marker(L.latLng(parseFloat(data.rivers[river].latitude), parseFloat(data.rivers[river].longitude))); marker.bindPopup(popup); } }); function onClickMoreDetails(data){ console.log(data); } 

First of all I didn't use any ids in template that might be duplicated.

Second – to determine which river's info you want to show I used data attribute data-river="'+i+'" on more info button.

And after all in mouse click handler get data attribute value from event.target and retrieve your data from an objects map.

function onClickMoreDetails(event){
  console.log(data.rivers[event.target.dataset['river']]);
}

Check this out: https://jsfiddle.net/fqL9g6cb/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM