Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将.each()转换为for循环jQuery_Jquery - Fatal编程技术网

将.each()转换为for循环jQuery

将.each()转换为for循环jQuery,jquery,Jquery,当前函数需要很长时间循环,并影响应用程序的性能。有人能帮我把每个()函数转换成for循环吗?谢谢 $('.scrollable tr:last').find('input[name="resource_week_value[]"]').each(function() { var pos = $(this).closest('td').prevAll().length; var tot = 0; var that = this;

当前函数需要很长时间循环,并影响应用程序的性能。有人能帮我把每个()函数转换成for循环吗?谢谢

  $('.scrollable tr:last').find('input[name="resource_week_value[]"]').each(function() {
        var pos = $(this).closest('td').prevAll().length;
        var tot = 0;
        var that = this;
        var temp = $(this).closest('tr').prevAll().find('td:eq(' + pos + ')').find('input[name="resource_week_value[]"]').each(function() {
            tot += +$(this).val();
            $(that).val(tot);
        });
    }); 

这难道不管用吗

$('input[name="resource_week_value[]"]').each(function() {
        var pos = $(this).closest('td').prevAll().length;
        var tot = 0;
        var that = this;
        var temp = $(this).closest('tr').prevAll().find('td:eq(' + pos + ')').find('input[name="resource_week_value[]"]').each(function() {
            tot += +$(this).val();
    });
}); 

如果没有标记,很难判断代码在做什么,但以下猜测可能会帮助您找到更好的重新编写代码的方法:

$('.scrollable tr').last().find('tr').each(function(i, v) {
    var that = $(this),
        tot = that.find('td').map(function(k,l){ return 0; }).get();
    that.prevAll().each(j,u) {
        tot = $(this).find('td').map(function(k,l) { 
            return +$(l).find('input[name="resource_week_value[]"]').val() + tot[k];
        }).get();
    });
    that.find('td').each(function(j,u) {
        $(u).find('input[name="resource_week_value[]"]').val( tot[ j ] );
    });
}); 

正如我在评论中提到的,你做错了两件事:

1) 您经常使用find()查询DOM树。而是使用合适的CSS选择器

2) 在$.each()循环中

您经常更新
input
的值,这不是必需的。在for-each循环中,每次使用
$(that).val(tot)DOM树受到影响

由于
tot
被分配给一个变量,在
each()
循环之外,放入
$(this).val(tot)
,这将以有效的方式为您提供相同的结果

3) 这不是性能改进,而是代码错误:

您使用的是
tot++$(this.val();


但是它应该是
tot+=$(this.val()在循环内部

也许你应该看看为什么代码需要这么长时间。不要认为更改为for循环会对性能产生很大影响。您可以尝试向要选择的输入添加类,这比通过名称选择它们要快得多。如果您向每个输入添加唯一的id,并使用
['id^=Resource\u week']
获取它,因为id选择器比类快!性能太差,因为您经常使用find()多次查询DOM树。相反,使用合适的CSS选择器来提高效率。共享您的HTML以提供更好的解决方案我已将该类添加到tr:last,并选择该类而不是find()。现在它的性能更好了。谢谢@mohamedrias的建议。
  var temp = $(this).closest('tr').prevAll().find('td:eq(' + pos +  ')').find('input[name="resource_week_value[]"]').each(function() {
                tot += +$(this).val();
                $(that).val(tot);
            });