14.数组去重
方法一:利用冒泡
function elementName(evt){
evt = evt|| window.event; // IE: window.event
// IE用srcElement获取事件源,而FF用target获取事件源
var selected = evt.target || evt.srcElement;
alert(selected.tagName);
}
window.onload = function(){
var el =document.getElementsByTagName('body');
el[0].onclick = elementName;
}
更简单:
document.onclick = function(e){
var e=(e||event);
var o=e["target"]||e["srcElement"];
alert(o.tagName.toLowerCase());
}
方法二:遍历
function getTagName(){
return document.getElementsByTagName("*");
} function stopPropagation(e) {
e = e || window.event;
if(e.stopPropagation) { //W3C阻止冒泡方法
e.stopPropagation();
} else {
e.cancelBubble = true; //IE阻止冒泡方法
}
}
window.onload=function(){
var tagObj=getTagName();
console.log("nihaofdfdfdfdfdfdf");
for(var i=0,max=tagObj.length;i<max;i++){
tagObj[i].onclick=function(e){ stopPropagation(e);
alert(this.tagName);
}
}
}
</script>