**题目:** JavaScript 中为 DOM 元素绑定事件可使用 `addEventListener` 来实现,但与之对应的事件移除方法 `removeEventListener` 却没有那么好用,例如它无法移除绑定的匿名方法。 请结合下面的代码,实现按钮点击一次后,移除自身绑定的匿名方法的功能。 ```js var btn = document.createElement('button'); btn.innerText = '按钮'; btn.addEventListener('click', function() { btn.innerText = '我被点击了-' + (+new Date()); }); document.body.appendChild(btn); ``` ---- **参考答案:** ```js window.HTMLElement && !function() { HTMLElement.prototype.addListener = function(type, fn, capture) { var el = this; fn = typeof fn === 'function' ? fn : function(){}; var bind = function() { el.addEventListener(type, fn, capture); return { removeListener: function() { el.removeEventListener(type, fn); } } }; return bind(); } }(); var btn = document.createElement('button'); btn.innerText = '按钮'; var evt = btn.addListener('click', function() { btn.innerText = '我被点击了-' + (+new Date()); evt.removeListener(); }); document.body.appendChild(btn); ```
Activity