2

就计算机资源而言,什么会更有效。将事件处理程序放在这样的循环中:

$('ul li').each(function()
{
    $(this).mouseover(function()
    {
        // code to do something 
    });

或者在循环之外拥有函数并在循环内创建对它的调用,如下所示:

$('ul li').each(function()
{
    $(this).mouseover(function()
    {
        doStuff($(this)); 
    });

function doStuff(liElem)
{
    // code to do something 
}

在我看来,第二个选项在计算机上会更容易,因为每次循环迭代时都不会重复执行某些操作的代码。事件处理程序的代码是每次循环都在计算机内存中创建,还是只创建一次?有什么想法吗?

4

1 回答 1

1

可以进行各种优化,但要针对您要求的方法进行优化,请在下面的代码中以内联注释的形式找到答案

第一种方法:

$('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
}
于 2012-12-30T22:40:29.660 回答