对象检测(object detection)
<pre name='code' class='js'>function attachEventListener(target, eventType, functionRef, capture)
{ if (typeof target.addEventListener != "undefined") { target.addEventListener(eventType, functionRef, capture); } else if (typeof target.attachEvent != "undefined") { target.attachEvent("on" + eventType, functionRef); }
}; W3C使用addEventListener,当我们使用的是firefox浏览器,那它将执行if语句,因为它定义了addEventListener,所以将执行: target.addEventListener(eventType, functionRef, capture); 如果当前使用的是ie浏览器,由于它没有定义addEventListener,即此时addEventListener返回的类型等于undefined,所以便执行else if语句,微软定义了另外一个作用等同于addEventListener的,即attachEvent: target.attachEvent("on" + eventType, functionRef); 这就是经常使用的技巧:对象检测(object detection)