问题描述
我尝试拼凑一个有点动态的Google地图显示时遇到了一些奇怪的问题。点击时,我在地图上覆盖了一个我想调用的函数。最初我把所有东西都硬编码了,所以我为每个覆盖层都有这样的功能:
$ bcode> function showArea(id){
return function(){
// do stuff with id
};
返回的函数关闭 id ,所以它继续引用它,并传递给 addListener 作为处理程序。
或者,您可以内联调用 showArea(1) ...
$的函数b $ bgoogle.maps.event.addListener(southEast,'click',function(){showArea(1);});
函数showArea(id){
//根据那个id做
}
这将起作用,因为您正在对 1 进行硬编码。如果它是一个可以改变的变量,就像在循环中一样,你可以使用第一个例子。
I'm having somewhat of an odd issue with trying to piece together a somewhat dynamic Google Maps display. I have overlays on a map that I would like to call a function when clicked. Initially I had everything hard coded, so I had a function for each overlay like this:
google.maps.event.addListener(southEast, 'click', showSouth); function showSouth() { // do stuff }This worked without a problem, but then I made the whole page more dynamic so I decided to make one function that would pass an ID and then display based on that, which is how I feel it should have been set up originally anyway. I altered the code to look more like this:
google.maps.event.addListener(southEast, 'click', showArea(1)); function showArea(id) { // do stuff based on that id }The function worked, but the problem is it gets called immediately on page load. After researching I've learned that when you call a function with the parentheses, that function gets called immediately and then it's return value is referenced. source
So now I'm a little stuck as to how exactly to go about passing that ID to the function without having it call the function immediately. I've found some hacky ways of doing it that might work, but I feel like this shouldn't be something I have to hack together...
解决方案Have showArea return a function that works with the id.
function showArea(id) { return function() { // do stuff with id }; }The returned function closes over id so it continues to reference it, and is passed to addListener to be used as the handler.
Alternately, you could just inline the function that calls showArea(1)...
google.maps.event.addListener(southEast, 'click', function() { showArea(1); }); function showArea(id) { // do stuff based on that id }This will work because you're hardcoding the 1. If it was a variable that could change, like in a loop, you'd use the first example.
这篇关于如何在不立即运行的情况下将参数传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!