笔试题之优化代码

请优化下段的代码
for(var i = 0; i < document.getElementsByTagName('a').length; i++) {
	document.getElementsByTagName('a')[i].onmouseover = function(){
	    this.style.color = 'red';
	};
	document.getElementsByTagName('a')[i].onmouseout = function(){
	    this.style.color = '';
	};
}

☛ 【优化1——> js 原生实现事件委托】:

var body = document.getElementById('body');

body.addEventListener('mouseover', function(e) {
	e = e || window.event;

	var target = e.target || e.srcElement;

	if (target.nodeName.toLowerCase() == 'a') {
		target.style.color = 'red';
	}
}, false);

body.addEventListener('mouseout', function(e) {
	e = e || window.event;

	var target = e.target || e.srcElement;

	if (target.nodeName.toLowerCase() == 'a') {
		target.style.color = '';
	}

}, false);

☛ 【优化2——> jQuery实现事件委托】:

var $body = $('body');

$body.on('mouseover', 'a', function() {
	this.style.color = 'red';
});

$body.on('mouseout', 'a', function() {
	this.style.color = '';
});

Scoop It and Enjoy the Ride!
原文地址:https://www.cnblogs.com/Ruth92/p/5836693.html