rsk*_*k82 4 javascript anonymous-function javascript-events
示例代码:
element.addEventListener('click',function () {
this.style.backgroundColor = '#cc0000'
//after element was clicked once what to do here to remove this event ?
},false)
Run Code Online (Sandbox Code Playgroud)
在哪里做,是否可以直接在我发表评论的功能?
如果添加事件,则addEventListener()必须具有对该功能的引用,以便随后将其删除.
使用匿名函数,arguments.callee只有当你在函数本身内时才能使用它:
element.addEventListener('click', function() {
this.style.backgroundColor = '#cc0000';
this.removeEventListener('click', arguments.callee);
}, false);
Run Code Online (Sandbox Code Playgroud)
但请注意,这在ES5"严格模式"中不合法.
因此,最好给回调一个名称,然后在调用中使用它removeEventLister():
element.addEventListener('click', function cb() {
this.style.backgroundColor = '#cc0000';
this.removeEventListener('click', cb);
}, false);
Run Code Online (Sandbox Code Playgroud)
演示http://jsfiddle.net/alnitak/RsaVE/
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |