Element/Delegation - MooTools 中文文档

返回介绍

Element/Delegation

发布于 2019-07-06 字数 2885 浏览 799 评论 0

Type: Element

扩展元素类型。

delegation是一个常用的方法侦听一个事件,此方法通过侦听父元素来捕获子元素事件,类似于Jquery的live方法,侦听动态内容和高交互页面时使用这个方法。

演示:

例如:

var myElement = $('myElement');
var request = new Request({
    // other options
    onSuccess: function(text){
        myElement.set('html', text); // No need to attach more click events.
    }
});
// 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')
    });
});

注意事项:

Element method: addEvent

通过父元素监听一个子元素,需要用css选择器指定父元素.否则将普通方法监听.

语法:

myElement.addEvent(typeSelector, fn);

参数:

  1. typeSelector – (string) 事件名称和css选择器。
  2. fn – (function) 事件函数.

例如:

// Alerts when an anchor element with class 'myStyle' is clicked inside of myElement
document.id(myElement).addEvent('click:relay(a.myStyle)', function(){
    alert('hello');
});
 
 
document.id('myElement').addEvent('click:relay(a)', function(event, clicked){
    event.preventDefault(); //don't follow the link
    alert('you clicked a link!');
    // You can reference the element clicked with the second
    // Argument passed to your callback
    clicked.setStyle('color', '#777');
});

返回:

  • (element) – 当前元素。

Element method: addEvents

添加多个事件。

例如:

$('myElement').addEvents({
    // monitor an element for mouseover
    mouseover: fn,
    // but only monitor child links for clicks
    'click:relay(a)': fn2
});

Element method: removeEvent

删除一个事件。

例如:

var monitor = function(event, element){
    alert('you clicked a link!');
};
 
$('myElement').addEvent('click:relay(a)', monitor);
// link clicks are delegated to element
 
// remove delegation:
$('myElement').removeEvent('click:relay(a)', monitor);

 

Element method: removeEvents

删除多个事件.

例如:

var monitor = function(){
    alert('you clicked or moused over a link!');
};
 
$('myElement').addEvents({
    'mouseover:relay(a)': monitor,
    'click:relay(a)': monitor
});
 
// link clicks are delegated to element
// remove the delegation:
$('myElement').removeEvents({
    'mouseover:relay(a)': monitor,
    'click:relay(a)': monitor
});
 
// remove all click:relay(a) events
$('myElement').removeEvents('click:relay(a)');

上一篇:Element/Event

下一篇:Element/Dimensions

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

目前还没有任何评论,快来抢沙发吧!