我已经构建了一个数据驱动的谷歌地图,其中包含不同的图标,这些图标会根据所找到的项目类型分配给地图。因此,如果我有5种类型的地标,每个都有不同的图标(商店,图书馆,医院等) - 我想要做的是动态生成谷歌图标对象。我在想这样的事情:
I've built a data-driven google map with different icons that get assigned to the map depending on the type of item located. So if I have 5 types of landmark, and each gets a different icon (store, library, hospital, etc.)-- what I'd like to do is generate the google icon objects dynamically. I was thinking something like this:
types = array('hospital','church','library','store',etc); var i=0; while (i<=types.length) { var landmark + i = new google.maps.Icon(); landmark.image = "icon" + i + ".png"; i++; }然而,正如您可能已经猜到的那样,这不起作用。我也试过使用eval,如下所示:
however, as you've probably guessed, this doesn't work. I also tried using eval, like this:
while (i<=types.length) { doIcon(i); i++; } function doIcon(i){ eval("var landmark" + i + " = new.google.maps.Icon();"); return eval("landmark" + i); }但它也不起作用 - 我很感激任何关于动态生成javascript变量。它必须是纯粹的js,我可以用PHP来做,但这不是一个选项。
but it didn't work either-- I'd appreciate any pointers on generating javascript variables dynamically. It's got to be pure js, I could do it in PHP but that's not an option here.
谢谢!
推荐答案这很容易做到: object [variablename] = what;
所以例如你可以有一个对象: var Landmarks = {} 你可以像这样添加它: Landmarks [地标+ i=新的google.maps.Icon(); 并以这种方式传递。
So for example you could have an object: var Landmarks = {} and you could add to it like so: Landmarks["landmark" + i] = new google.maps.Icon(); and pass it that way.
如果你需要这些变量 global (为什么会这样?)您可以使用窗口直接访问全局对象。
If you need these variables to be global (why would you?) you can access the global object directly using window.
更多推荐
有没有一种简单的方法来使用Javascript创建动态变量?
发布评论