[英]Can't get value from map in js
<div id="menu">
<ul>
<li><a href="/" id="main">Main</a></li>
</ul>
</div>
<script type="text/javascript">
var main = new Object();
main.menu_background_image = "url(images/main.png)";
function setMenuImages() {
var menuListArray = $$('#menu li');
var menuListArrayLength = menuListArray.length;
for(var k = 0; k < menuListArrayLength; k++) {
var listMenuId = menuListArray[k].getChildren('a').get('id');
menuListArray[k].setStyle('background-image', listMenuId['menu_background_image']);
}
}
</script>
I can't get value from map when I call setMenuImages() and I have no idea why :( I checked it with alert and it said "undefined". What i did wrong? 当我调用setMenuImages()并且我不知道为什么时,我无法从地图获取价值:(我用警报检查它并且它说“未定义”。我做错了什么?
well... 好...
var listMenuId = menuListArray[k].getChildren('a').get('id');
this will have an ARRAY of ids - like ['foo','bar'];
这将有一个ID的ARRAY - 如
['foo','bar'];
- with keys 0
, 1
, ... etc -连键
0
, 1
,...等等
you then try to reference it via a key that's not there of listMenuId['menu_background']
- which is how you'd retrieve a property from an object
. 然后尝试通过一个不存在
listMenuId['menu_background']
的键来引用它 - 这就是你从object
检索属性的方法。
also don't do main = new Object();
也不要做
main = new Object();
- see http://answers.oreilly.com/topic/2138-how-to-use-object-literals-in-javascript/ - do: - 请参阅http://answers.oreilly.com/topic/2138-how-to-use-object-literals-in-javascript/ - 执行:
var main = {
menu_background_image: "url(images/main.png)"
};
looks like you want to actually set the background image property on all found links to that one: 看起来你想在所有找到的链接上实际设置背景图像属性:
$$('#menu li a').setStyle('background-image', main.menu_background_image);
This you can do with 1 liner above but wouldn't it be better if you kept CSS/styles out of your javascript and put them into .css where they belong? 你可以使用上面的1个衬垫,但是如果你保留CSS /样式而不是你的javascript并将它们放入它们所属的.css中会不会更好?
if you have more than one you could potentially do something like: 如果你有多个,你可以做以下事情:
var tpl = 'url(images/{id}.png)';
// proper menu items image hash map based upon id as key
var menu = {
main: 'someimage',
other: 'otherimage'
};
$$('#menu li a').each(function(link){
var id = link.get('id');
link.setStyle('background-image', tpl.substitute({id: id}));
// or read from an object like this with fallback
link.setStyle('background-image', menu[id] || tpl.substitute({id: id}));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.