简体   繁体   中英

How to add an event to an element just created?

How can I add an event (by Mootools) to an element just created via set("html") , and inserted through the DOM?

$(document).addEvent("domready", function(){
      $(someel).set("html", "<p class='someclass'></p>");
      $$("someclass").somefn("click", function(){...});//somefn: that add the "click" event to the <p> element

});

So. via event delegation, adding a single event to top most element:

document.addEvent("domready", function(){
    $('foo').addEvents({
        'click:relay(p.someclass)': function(){
            alert('very well');
        }
    }).set("html", "<p class='someclass'>click me</p>");
});

or chaining it like so, adding events to all elements directly:

document.addEvent("domready", function(){
    $('foo').set("html", "<p class='someclass'>click me</p>")
        .getElements('.someclass').addEvent('click', function(){
            alert('chained');
        });
});

method 1 is more performant and allows for adding/removal or matching elements without rebinding.

You should use the Element constructor . A code example could be like this:

$(document).addEvent("domready", function () {
    var pElement = new Element('p', {           // create a new element
        'class': 'someclass',                     // give it a class
        'html': 'Click me to make me alive...'  // give it some HTML
    });

    $('someel').adopt(pElement);                // have someone adopt it
    pElement.addEvent("click", function () {    // add event to it here OR in the Element constructor
        alert('Hello world!'); 
    });
});

Example

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