MooToolsはイベントの委任もサポートしています。ドキュメントの例を次に示します。
// Adding the event, notice the :relay syntax with the selector that matches the target element inside of myElement.
// Every click on an anchor-tag inside of myElement executes this function.
myElement.addEvent('click:relay(a)', function(event, target){
event.preventDefault();
request.send({
url: target.get('href')
});
});
したがって、推測では(私はMooToolsを使用したことがありません)、myClass
問題の要素にクラスを追加した場合は、次のようになります。
window.addEvent('domready', function() {
$(document).addEvent('click:relay(.myClass)', function() {
// One of the elements was clicked
});
});
イベントの委任をサポートしていない古いバージョンのMooToolsを使用している場合は、問題ありません。自分で行うことができます。基本的に、イベントをコンテナにフックし(可能性がありますがdocument.body
、可能であれば、要素を追加する場所の近くで実行します)、イベントが発生しevent.target
たら、を見てください。これにより、イベントの実際の要素がわかります。で発生しました。から始めてevent.target
、各親をチェックして、が含まれているかどうかを確認しますmyClass
。その場合は、イベントを処理します。大まかに:
$(container).addEvent('click', function(event) {
var match, elm;
for (elm = event.target; !match && elm; elm = elm.parentNode) {
if ($(elm).hasClass("myClass")) {
match = elm;
}
}
if (match) {
// Yup, its a "myClass" element -- process the click
}
});