简体   繁体   中英

Add event to dynamically generated element

How can I add an event to an element which was loaded by AJAX.

jQuery has live , but what's the Mootools equivalent?

For example:

window.addEvent('domready', function() {
    // some code which loads new elements by ajax

    // Filter
    $$('.filterButton').addEvent('click', function(event) {
        alert('wow');
    });
});

the mootools equivalent is via delegatorElement.addEvent("event:relay(mask)", fn); where event can be standard bubbling (click, mouseover/out/leave/enter etc) or non-bubbling (blur, focus, change etc).

in your code that goes as:

$(document.body).addEvent("click:relay(.filterButton)", function(event, element) {
    console.log(event, element === this); // event obj, true
});

it's better to add the event to an element higher up the dom, like document.id("delegatorId")

more here:

http://mootools.net/docs/core/Element/Element.Delegation

keep in mind, event delegation is in mootools-core since 1.4 - it used to be in mootools-more before that, which means a custom build.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM