我对您的问题的理解是您正在尝试在地图之间切换,并且当您切换时,单击事件处理程序会附加到地图链接。
首先对于切换,您需要跟踪哪个是可见的,以便您可以正确隐藏它并使另一个可见:
var unique_link = $$('#my_unique_id a'),
// keep track of which map is visible
currentMap = map1;
unique_link.addEvent('click', function(e){
// Prevent the default behavior, but still allow bubbling of events
e.preventDefault();
// Hide the current map
currentMap.setStyle('display', 'none');
// store the correct map by comparing the two maps and making it visible
currentMap = (currentMap == map1 ? map2 : map1).setStyle('display', 'block');
});
澄清一下,currentMap = (currentMap == map1 ? map2 : map1)
称为三元运算。它是 if/else 的简写,可以重写为:
if (currentMap == map1) {
currentMap = map2;
} else {
currentMap = map1;
}
currentMap.setStyle('display', 'block');
接下来,为什么要去掉每张地图的链接上的事件呢?当您在地图之间切换时,它们不能保持连接吗?
最后,您询问了事件委托和单击时访问值的问题。以下是它在 MooTools 中如何工作的示例:
// We pass an array of map1 and map2 through $$ to make sure that the returned value is an element collection
// So we can use addEvent on both elements.
// The event "type" we would have passed to addEvent has changed, using a psuedo event called "relay", which handles event delegation
// It takes a selector for matching elements
// The function that is passed to addEvent has two arugments, e, which is the event object, and element, which is the element that the
// event is being delegated to.
$$([map1, map2]).addEvent('click:relay(a)', function(e, element){
// Prevent the default behavior of the anchors
e.preventDefault();
// element argument is the anchor. So you can access it this way.
element.get('href');
// or "this" can also be used.
this.get('href');
});