gpt4 book ai didi

javascript - jQuery 循环内嵌套函数的效率

转载 作者:行者123 更新时间:2023-11-30 05:52:05 24 4
gpt4 key购买 nike

在计算机资源方面什么会更有效率。将事件处理程序放入这样的循环中:

$('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
}

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

最佳答案

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

第一种方法:

$('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
}

关于javascript - jQuery 循环内嵌套函数的效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14095168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com