可以进行各种优化,但要针对您要求的方法进行优化,请在下面的代码中以内联注释的形式找到答案
第一种方法:
$('ul li').each(function()
{
// Maybe you might like to declare some variables here
$(this).mouseover(function()
{
// code to do something
// Maybe you might like to use the variables declared in above function
// Disadvantage over other approach
// The code written here will need to store the context information of the outer function and global context
// Advantage over other approach
// You can directly access the variables declared in the above function
});
}
或者在循环之外拥有函数并在循环内创建对它的调用,如下所示:
第二种方法:
$('ul li').each(function()
{
// Maybe you might like to declare some variables here
$(this).mouseover(function()
{
doStuff($(this));
});
});
function doStuff(liElem)
{
// code to do something
// Advantage over other approach
// The code written here will need to store the context information only for the global context
// Disadvantage over other approach
// You cannot directly access the variables declared in the outer function as you can in the other approach,
// you will need to pass them to the doStuff function to access here
}