我有一个动态生成的对象,如下所示:
colorArray = {
AR: "#8BBDE1",
AU: "#135D9E",
AT: "#8BBDE1",
... }
我试图用它来为地图着色这个插件以及调用插件期间的“颜色”属性。像这样:
$('#iniDensityMap').vectorMap({
backgroundColor: '#c2e2f2',
colors: colorArray,
... (some other params)
});
但在其他国家却没有什么影响。当我对此进行硬编码时,它工作正常 - 但它必须为该项目动态生成,因此这样的东西对我不起作用(尽管它实际上确实为地图着色):
$('#iniDensityMap').vectorMap({
backgroundColor: '#c2e2f2',
colors: { AR: "#8BBDE1", AU: "#135D9E", AT: "#8BBDE1" },
... (some other params)
});
我已经在插件中深入追踪了这个问题,发现它与这个循环有关:
setColors: function(key, color) {
if (typeof key == 'string') {
this.countries[key].setFill(color);
} else {
var colors = key; //This is the parameter passed through to the plugin
for (var code in colors) {
//THIS WILL NOT GET CALLED
if (this.countries[code]) {
this.countries[code].setFill(colors[code]);
}
}
}
},
我也尝试过迭代colorArray
我自己在插件之外对象,我遇到了同样的问题。无论里面装着什么for ( obj 中的 var x )没有开火。我也注意到了colorArray.length
回报不明确的。另一个重要的注意事项是我已经实例化了var colorArray = {};
在一次单独的调用中,试图确保它位于全局范围内并且能够被操纵。
我认为问题在于:
- 我动态填充对象的方式 -
colorArray[cCode] =
cColor;
(在 jQuery .each 调用中)
- 我再次混淆了 javascript 中 Arrays() 和 Objects() 之间的区别
- 也许这是一个范围问题?
- 以上所有内容的某种组合。
EDIT #1:我已将有关 Firebug 控制台中的对象的附加问题移至新帖子HERE。这个问题更具体地涉及 Firebug,而不是我在这里询问的底层 JS 问题。
编辑#2:附加信息这是我用来动态填充对象的代码:
function parseDensityMapXML() {
$.ajax({
type: "GET",
url: "media/XML/mapCountryData.xml",
dataType: "xml",
success: function (xml) {
$(xml).find("Country").each(function () {
var cName = $(this).find("Name").text();
var cIniCount = $(this).find("InitiativeCount").text();
var cUrl = $(this).find("SearchURL").text();
var cCode = $(this).find("CountryCode").text();
//Populate the JS Object
iniDensityData[cCode] = { "initiatives": cIniCount, "url": cUrl, "name": cName };
//set colors according to values of initiatives count
colorArray[cCode] = getCountryColor(cIniCount);
});
}
});
} //end function parseDensityMapXML();
然后,在页面其他位置的复选框的单击事件上调用此函数。对象iniDensityData
and colorArray
在 html 文件的头部声明 - 希望将它们保留在全局范围内:
<script type="text/javascript">
//Initialize a bunch of variables in the global scope
iniDensityData = {};
colorArray = {};
</script>
最后,这是正在读取的 XML 文件的片段:
<?xml version="1.0" encoding="utf-8"?>
<icapCountryData>
<Country>
<Name>Albania</Name>
<CountryCode>AL</CountryCode>
<InitiativeCount>7</InitiativeCount>
<SearchURL>~/advance_search.aspx?search=6</SearchURL>
</Country>
<Country>
<Name>Argentina</Name>
<CountryCode>AR</CountryCode>
<InitiativeCount>15</InitiativeCount>
<SearchURL>~/advance_search.aspx?search=11</SearchURL>
</Country>
... and so on ...
</icapCountryData>