简体   繁体   English

如何向刚创建的元素添加事件?

[英]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?如何将事件(通过 Mootools)添加到刚刚通过set("html")创建并通过 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.方法 1 的性能更高,并且允许添加/删除或匹配元素而无需重新绑定。

You should use the Element constructor .您应该使用Element 构造函数 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例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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