Hi i have this JavaScript Code. But i get the error: "Uncaught ReferenceError: saveMarker is not defined"
from the console when i click the "save" button. I call the code below from my "main" HTML file with a script block. The Popup is functioning but when i klick on save the error comes up.
I use it with the leaflet library which is referenced by the "L" if someone is wondering. I also added a picture of the project.
I Tried this Version:
export function markerpopup(map, latlng) {
console.log("starte markerpopup");
var actual_location = "";
var popupContent = `
<button onclick="saveMarker()">Speichern</button>`;
L.popup()
.setLatLng(latlng)
.setContent(popupContent)
.openOn(map);
}
function saveMarker() {
console.log("starte saveMarker");
}
And this Version (Which should be the same as https://www.w3schools.com/JSREF/event_onclick.asp):
export function markerpopup(map, latlng) {
console.log("starte markerpopup");
var actual_location = "";
var popupContent = `
<button onclick="saveMarker()">Speichern</button>
<script>
function saveMarker() {
console.log("starte saveMarker");
}
</script>`;
L.popup()
.setLatLng(latlng)
.setContent(popupContent)
.openOn(map);
}
Would appreciate if someone could help!
Tried different places to place the saveMarker
function.
3
Answers
Since you are using
export
syntax, I assume that you are using an es6 module, and a
<script type="module">
tag. if this is true, then your function declaration is scoped in the module, and not the whole page. You need to do something like this:what you can try to do is
or you can try
Instead of passing a string to
setContent()
you could pass anHTMLElement
.You can create one by calling
document.createElement()
, then attach the event handler withaddEventListener()
and set the content withappend()
,innerHTML
, or any other method to update the contents of anHTMLElement
.