0

我有两张地图:

var map1 = document.id('map1');
var map2 = document.id('map2');

第二张地图是隐藏的。

map2.setStyle('display','none');

在第一个地图上,有一个元素(链接)具有唯一的 id - 单击此元素时我想运行另一个函数(隐藏第一个地图并显示第二个地图)。

我有:

  var links = document.id('map1').getElements('a');     

  links.each(function(link) { 
  link.addEvent('click', function(e) {
   e.stop();
    //do something with links
  });

我尝试这样的方式:

var unique_link = document.id('my_unique_id').getElements('a');

unique_link.addEvent("click", function(){
links.removeEvent('click');
map1.setStyle('display','none');
map2.setStyle('display','block');
var links = document.id('map2').getElements('a'); 
});

但是当我点击这个独特的元素时,第一个功能仍在运行。

4

2 回答 2

1

我对您的问题的理解是您正在尝试在地图之间切换,并且当您切换时,单击事件处理程序会附加到地图链接。

首先对于切换,您需要跟踪哪个是可见的,以便您可以正确隐藏它并使另一个可见:

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');

});
于 2012-06-15T00:07:50.763 回答
1

Element.removeEvent不能这样工作。它要求您同时传递事件的名称(单击)和处理它的函数。这是因为可能有多个函数在click被触发时被调用。您可以使用Element.removeEvents删除所有点击处理功能,但这可能不是您真正想要的(尽管它可能没问题)。为了做到最好,你会这样做:

var handler = function(e) { e.stop(); /* do something with links */ }),
    links = document.id('map1').getElements('a');

links.addEvent('click', handler);

document.id('my_unique_id').getElements('a').addEvent('click', function() {
    links.removeEvent('click', handler);
    /* Other stuff */
});

哦,顺便说一句,这个:

document.id('some_id').getElements('.some-selector');

可以这样写:

$$('#some_id .some-selector');
于 2012-06-14T08:07:33.400 回答