使用这段HTML:
<div id="modal">
<select class="country">
<option value=""></option>
<option value="opt">Opt</option>
</select>
</div>
这段JS:
$('modal').addEvent('change:relay(.country)', function(){
console.log(this); // "this" refers to #modal.
}).fireEvent('change:relay(.country)');
日志显示this
关键字引用了#modal元素。我想为每个.country select触发事件,并在回调中引用每个事件。我怎么能得到它呢?这是小提琴:http://jsfiddle.net/EWUCG/5/
从IRC频道聊天:
- 事件委托基于事件冒泡。
- 所以父元素中的元素将触发一个事件。然后它将触发它的父节点中的事件…
- 它会一直这样做,直到没有父级(window)
- 所以你实际上只是设置回调发生当其中一个父级接收到从它的子级传递过来的事件。
我剩下的唯一解决方案是"教学":
$('modal').addEvent('change:relay(.country)', function(event, target){
console.log(this, event, target); // Then "this" refers to each .country select.
});
$$('.country').each(function(el){
$('modal').fireEvent('change', [null, el]);
});
小提琴:http://jsfiddle.net/EWUCG/12/
$$('.country').addEvent('change', function(){
console.log(this);
// "this" refers to select
console.log(this.getElement(':selected'));
// this.getElement(':selected') refers to selected option
}).fireEvent('change');
这可能就是你想要的…这是我一年前在IRC里看到的,我不能告诉你是谁提供的。
http://jsfiddle.net/prbNK/7/和一个Element方法可以更好地重用代码- http://jsfiddle.net/prbNK/12/