Mar*_*aio 10 javascript events event-handling javascript-events
为了添加事件,我们可以使用这个简单的第一个解决方案:
function AddEvent(html_element, event_name, event_function)
{
if(html_element.attachEvent) //Internet Explorer
html_element.attachEvent("on" + event_name, function() {event_function.call(html_element);});
else if(html_element.addEventListener) //Firefox & company
html_element.addEventListener(event_name, event_function, false); //don't need the 'call' trick because in FF everything already works in the right way
}
Run Code Online (Sandbox Code Playgroud)
或者这第二个解决方案(添加内联事件):
function AddEvent(html_element, event_name, event_function)
{
var old_event = html_element['on' + event_name];
if(typeof old_event !== 'function')
html_element['on' + event_name] = function() { event_function.call(html_element); };
else
html_element['on' + event_name] = function() { old_event(); event_function.call(html_element); };
}
Run Code Online (Sandbox Code Playgroud)
这些都是跨浏览器,可以这种方式使用:
AddEvent(document.getElementById('some_div_id'), 'click', function()
{
alert(this.tagName); //shows 'DIV'
});
Run Code Online (Sandbox Code Playgroud)
由于我attachEvent/addEventListener在事件处理实现中使用的感觉更多,我想知道:
使用我可能更清楚的第二种解决方案是否有任何缺点/缺点?
我可以看到两个,但我对更多(如果有的话)感兴趣:
html_element['on' + event_name] = null)相关的所有函数,但我不能用于detachEvent/removeEventListener删除确切的特定函数.任何答案,如:"使用jQuery"或任何其他FW是毫无意义的!
使用第二个解决方案,您必须手动调用以前的函数,这使得很难删除特定的侦听器(对我而言,这听起来像是您想要清除所有侦听器的东西),而在第一个解决方案中,您只能除非你想模仿第一个功能,否则同时清除它们.
就个人而言,我总是使用第一种解决方案,因为它具有不必担心清除可能的其他事件监听器的优点.
在Mozilla的维基还列出了第一个解决方案工作于任何DOM元素,而不仅仅是HTML元素上的优势,而且它更精细允许在相当听众被激活与第三个参数的细粒度控制(捕获与冒泡).
| 归档时间: |
|
| 查看次数: |
12099 次 |
| 最近记录: |