开发者

Quick question about jQuery selector content efficiency

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜