之前做了淘宝给的面试题,其中一题是 页面有 一个ul 里面有 n 个li, 而每个li在 mouseover 的时候,需要执行相应的function。 一般来做,我们会在每个 li上绑定 mouseover事件。而这套题的重点是怎么优化代码,提高效率。 在舜子提供的思路下,是把事件绑定在 li 的父级 ul 上面。 通过event 来判断当前对象。 这个思路,我感觉是叫时间委托吧,呵呵。代码如下:
function delegate(e){
e = e || window.event;
return e.target || e.srcElement;
}
$("ul").bind("mouseover",function(e){
var t = delegate(e), o=$(t),ul=o.parent(); //找到当前的对象
if(o.is('li') && ul.is('ul')) //判断对象
{
do something...
}
})

reply