问题
I've created a simple js project which plots a series of points using leaflet.js.
I then want to populate an info window with point specific data with an on click event. But I can't seem to get it to work.
This is roughly what I've done:
var circle = L.circle(
[data[i]['latitude'], data[i]['longitude']],
50,
{ color: 'red', fillColor: 'red', fillOpacity: .5}
).addTo(map)
.bindPopup(data[i]['SCHNAME'])
.on('click', fill_info_window(data, i));
function fill_info_window(data, i){ /* fill data */ }
Unfortunately, it automatically fills the window with the latest data.
Why isn't it working?
You can see the project here:
http://www.thisisstaffordshire.co.uk/images/localpeople/ugc-images/275796/binaries/leaguetableTemplate.html
回答1:
On this line:
.on('click', fill_info_window(data, i));
...you're calling the fill_info_window function, not just referring to it. You want to do something like this:
.on('click', function() {
fill_info_window(data, i);
});
unless you're in a loop (that i variable makes me think maybe you are). If you are, then:
.on('click', makeHandler(data, i));
...where makeHandler looks like this:
function makeHandler(theData, index) {
return function() {
fill_info_window(theData, index);
};
}
The reason you don't want my first answer in a loop is that all of the handlers will refer to the same data and i variables, and see their value as of when the handler is called, not when it's registered. That's why we use the makeHandler function instead, so it creates a closure over something that doesn't change. More on my blog: Closures are not complicated
回答2:
You probably want to bind the function as a handler, not its result from calling it. So remove the invocation and use ….on('click', fill_info_window);. See also this quirksmode article about event handling: No parenthesis!.
来源:https://stackoverflow.com/questions/13857225/why-is-my-click-function-not-working-as-expected