如何将事件(由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
});
答案 0 :(得分:3)
因此。通过事件委托,将单个事件添加到最顶层的元素:
document.addEvent("domready", function(){
$('foo').addEvents({
'click:relay(p.someclass)': function(){
alert('very well');
}
}).set("html", "<p class='someclass'>click me</p>");
});
或者像这样链接它,直接向所有元素添加事件:
document.addEvent("domready", function(){
$('foo').set("html", "<p class='someclass'>click me</p>")
.getElements('.someclass').addEvent('click', function(){
alert('chained');
});
});
方法1性能更高,允许添加/删除或匹配元素而无需重新绑定。
答案 1 :(得分:0)
您应该使用Element constructor。代码示例可能是这样的:
$(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!');
});
});