笔试题之优化代码

请优化下段的代码
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 = '';
});

posted on 2016-09-03 12:08  Ruth92  阅读(219)  评论(0编辑  收藏  举报

导航