我正在尝试自学HTML5和JavaScript,并感谢任何帮助。 我通过使用eval()解决了一个问题,并想知道是否有其他方法可以在不使用eval()的情况下解决它。我尝试过的所有东西似乎都不起作用。
我有两个数组,定义如下:
var europe = {
shapes: {
AL: "M520.651,114.27l-0.257,0.900l0.385,1.160l1.029,0.643l0,0.644l-0.901,0.386l-0.128,0.901l-1.288,1.287l-0.386-0.128l-0.127-0.644l-1.417-0.900l-0.259-1.288l0.259-1.803l0.256-0.901l-0.384-0.386l-0.258-0.901l1.287-1.288l0.129,0.516l0.771-0.258l0.516,0.773l0.643,0.257l-0.130-1.030z",
AM: "M582.697,116.33l3.605,-0.515l0.642,0.772l1.032,0.386l-0.516,0.773l1.416,0.900l-0.772,0.902l1.159,0.643l1.158,0.516l0.129,1.801l-1.029,0.129l-1.032,-1.544l0,-0.515l-1.287,0.129l-0.771,-0.772l-0.516,0l-1.029,-0.773l-2.059,-0.643l0.256,-1.288l0.386,0.901z",
AT: "M510.996,97.278l-0.257,1.158l-1.545,0l0.643,0.643l-0.900,1.674l-0.515,0.515l-2.446,0l-1.289,0.644l-2.315-0.258l-3.734-0.644l-0.644-0.900l-2.703,0.386l-0.258,0.514l-1.672-0.386l-1.416,0l-1.160-0.514l0.385-0.644l-0.128-0.515l0.903-0.128l1.285,0.772l0.387-0.772l2.446,0.128l1.931-0.515l1.287,0.128l0.773,0.515l0.258-0.386l-0.387-1.802l1.030-0.386l0.901-1.158l2.058,0.772l1.417-1.030l1.030-0.258l2.061,0.901l1.286-0.129l1.158,0.516l-0.127,0.256l-0.257-0.903z",
},
names: {
AL: "Albania",
AM: "Armenia",
AT: "Austria",
}
};
我正在做的是遍历europe.shapes中的路径数据来绘制它,然后使用以下代码在europe.names中显示匹配的数据:
for(var euroKey in europe.shapes) {
var pathEuro = new Kinetic.Path({
data: europe.shapes[euroKey],
name: euroKey,
fill: 'yellow',
stroke: '#555',
strokeWidth: 1
});
pathEuro.on('mouseover', function() {
var euroText = eval('europe.names.'+this.getName());
writeMessage(euroText);
this.setFill('#CCCCCC');
this.moveTo(topLayer);
topLayer.drawScene();
});
pathEuro.on('mouseout', function() {
writeMessage('');
this.setFill('#eee');
this.moveTo(mapLayer);
topLayer.draw();
});
textLayer.add(countryText);
mapLayer.add(pathEuro);
};
这主要是从这里的教程中偷来的:http://www.html5canvastutorials.com/labs/html5-canvas-world-map-svg-path-with-kineticjs/但我试图添加国家/地区名称的鼠标悬停文本。 使用eval()的方法很有效,但是当我自己这样做时,我不想学习坏习惯。
整个代码在GitHub上了:https://github.com/malkie-labs/html5-world-map如果有人真的,真的很无聊并想看一看。任何建设性的批评或建议都表示赞赏!
谢谢! 斯科特
答案 0 :(得分:1)
如果您只使用eval
来访问变量名对象成员,则无法使用eval:
eval('europe.names.'+this.getName());
简单地变成
europe.names[this.getName()];