您的位置:首页 > 编程语言

笔试题之优化代码

2016-09-03 12:08 281 查看
请优化下段的代码
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 = '';
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: