开发者

Quick question about jQuery selector content efficiency

开发者 https://www.devze.com 2023-01-16 21:42 出处:网络
I am loading HTML page through ajax and then doing a bunch of searches using selectors: $.ajax({ ... dataType: \"html\",

I am loading HTML page through ajax and then doing a bunch of searches using selectors:

$.ajax({
    ...
    dataType: "html",
    success: function(html) {
        $("#id1", html);
        $(".class", html);
        //...
    }
}

Should I extract $(html) into a开发者_StackOverflow中文版 variable and use it as a content, or it doesn't matter (from performance point)?

success: function(html) {
        $html = $(html);
        $("#id1", $html);
        $(".class", $html);
        //...
    }


You should always minimize number of $() calls, as they are expensive. Every one of these calls constructs new JQuery object, so saving these objects to variables is a good thing to do.


I would do this:

success: function(html) {
            $(html)
                .find("#id1").do().do().end()
                .find(".class").do().end();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消