开发者

Mootools addEvent with multiple id's

How can I use this function more times:

$('GotoHome').addEvent('click', function(event) {
    event = new 开发者_如何学JAVAEvent(event).stop();
    scroll.toElement('middlerightwrapper');
});

If I create multiple links with the ID="GotoHome" it doesn't work anymore, only with one ID. I don't want to duplicate like, GotoHome1, GotoHome2, GotoHome3


I would suggest adding a common class to your elements and using the dollars function to add the click hander:

HTML

<a href="" class="common-class" id="GotoHome1">Goto Home 1</a>
<a href="" class="common-class" id="GotoHome2">Goto Home 2</a>
<a href="" class="common-class" id="GotoHome3">Goto Home 3</a>

Mootools

$$('.common-class').addEvent('click', function(event) { 
    event = new Event(event).stop(); 
    scroll.toElement('middlerightwrapper'); 
});

The dollars function returns an array of all elements that match the selector.


You can't have more than an element with a in (eg: id MUST be unique on your page), it is not a mootools issue or requirement, it is a html one (though browser forgive a lot loose programs).

You shoud rely on classes other than id

$$('.GotoHome').addEvent('click', function(event) { 
     event = new Event(event).stop(); scroll.toElement('middlerightwrapper'); }
);

or, if you have an enclosing container you can use event delegation to have a single entry point instead of multiple addEvent function:

 $('container-id').addEvent("click:relay(.GotoHome)", function(event) { 
     event = new Event(event).stop(); scroll.toElement('middlerightwrapper'); }
);

I'm not on my development workstation and can't check for the relay syntax in event manager, It will worth a check

Edit

Hint on delegating events from mootools official site

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜