笔试题之优化代码

请优化下段的代码
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   Ruth92  阅读(221)  评论(0编辑  收藏  举报

导航

< 2025年1月 >
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8

统计

点击右上角即可分享
微信分享提示