简体   繁体   English

如何在此函数中优化和减少对jQuery的调用?

[英]How can I optimize and reduce the calls to jQuery in this function?

I have a code that seems to be not optimal. 我的代码似乎不是最佳的。 I would like to reduce content of Reorder function to single jquery function. 我想将Reorder函数的内容减少到单个jquery函数。 It can be done simpler or maybe this is a good approach? 可以更简单地完成它,或者这也许是个好方法?

HTML: HTML:

<div id="sortable">
     <div class="i">
        @<input type="text" name="first" value="" />
     </div>
    <div class="i">
        @<input type="text" name="last" value="" />
    </div>
</div>
<a href="#" id="add_input">Add</a>

JS: JS:

$(function(){
    $("#sortable").sortable({
        containment: "document",
        axis: "y",
        update: Reorder,
    });
    function Reorder()
    {        
        $("#sortable input").attr("name", function(i){
            //if(i==0){return "first";}
            //else{return "waypoint" + (i + 1); }
            return "middle" + i;
        });
        $("#sortable input:first").attr("name", "first");
        $("#sortable input:last").attr("name", "last");
    }
    $("#add_input").click(function () {
        var inputIndex = $("#sortable > .i").length;

        $("#sortable input:last").attr("name", function(){
            return "middle" + (inputIndex - 1);
        });

        if(inputIndex>1){
            var html = '<div class="i">';
            html += '@<input type="text" name="last" value="" /> ';
        }

        $("#sortable").append(html); 
        return false;
    });
});

DEMO: jsfiddle 演示: jsfiddle

Here is a little bit optimized version: 这是一些优化的版本:

$(function(){

    var $sortable = $('#sortable');

     $sortable.sortable({
        containment: "document",
        axis: "y",
        update: Reorder,
    });

    function Reorder()
    {        
        var $inputs = $sortable.find('input');
        $inputs.each(function(i, elm) {
            this.name = 'middle' + i;
        });
        $inputs
            .filter(':first').attr('name', 'first')
            .end()
            .filter(':last').attr('name', 'last');
    }

    $("#add_input").click(function () {

        var inputIndex =  $sortable.children(".i").length;

        $sortable.find('input:last').attr('name', 'middle' + (inputIndex-1));

        if( inputIndex > 1)
        {
            $('<div class="i">@<input type="text" name="last" value="" /></div>')
                .appendTo($sortable);
        }

        return false;
    });
});


  • Cache your jquery objects to avoid re-querying all the time the same thing: $('#sortable') 缓存您的jquery对象,以避免一直重复查询同一对象: $('#sortable')

  • No need to use .attr(string, function) to simply concatenate a string, use .attr('name', 'middle' + (inputIndex-1)) 无需使用.attr(string, function)来简单地连接字符串,请使用.attr('name', 'middle' + (inputIndex-1))

  • jquery is about chaining, abuse it: $inputs.filter().attr().end().filter().attr() jQuery是关于链接的,请滥用它:$ inputs.filter()。attr()。end()。filter()。attr()

I've made this fiddle to illustrate. 我做了这个小提琴来说明。


Event more optimized :o) 活动更加优化:o)

You could also write your Reorder() function this way. 您也可以通过这种方式编写Reorder()函数。 Seems a bit 'stupid' to loop and then re-filter again. 似乎有点“愚蠢”地循环,然后再次重新过滤。 Do everything in the loop: 循环执行所有操作:

function Reorder()
{        
    var $inputs = $sortable.find('input');

    $inputs.each(function(i, elm) {
        this.name = i == 0
            ? 'first'
            : i == ($inputs.length-1)
                ? 'last'
                : 'middle' + i;
    });
}

There is not much wrong with your existing Reorder function. 您现有的“重新排序”功能没有多大问题。 You could very slightly improve it like so: 您可以这样稍微改善一下:

function Reorder() {
    var sortableInput = $("#sortable input");
    sortableInput.attr("name", function(i) {
        //if(i==0){return "first";}
        //else{return "waypoint" + (i + 1); }
        return "middle" + i;
    });
    sortableInput.filter(":first").attr("name", "first");
    sortableInput.filter(":last").attr("name", "last");
}

That reduces the number of look-ups of #sortable input from three to one. 这样可以将#sortable input的查找#sortable input从三个减少到一个。

You could also leave out the variable declaration and just string it all together, like so: 您还可以省略变量声明,然后将其全部串在一起,如下所示:

function Reorder() {
    $("#sortable input").attr("name", function(i) {
        //if(i==0){return "first";}
        //else{return "waypoint" + (i + 1); }
        return "middle" + i;
    }).filter(":first").attr("name", "first").end().filter(":last").attr("name", "last");
}

Personally, I find that a bit harder to read than the previous example. 就个人而言,我发现比上一个示例更难读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM