さまざまな最適化が可能ですが、それをあなたが求めたアプローチに固有に保つために、以下のコードのインラインコメントとして答えを見つけてください
最初のアプローチ:
$('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
});
}
または、ループの外側に関数を設定し、次のようにループ内で関数の呼び出しを作成します。
2番目のアプローチ:
$('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
}