代码之家  ›  专栏  ›  技术社区  ›  Chad

jQuery:单独追加还是一次性追加+选择器?

  •  3
  • Chad  · 技术社区  · 16 年前

    我正在构建一个jQueryUI小部件,当我初始化时,我创建了几个div、锚点和输入。我已经读到,构建一个完整的HTML字符串并将其附加到DOM比附加每个单独的DOM元素更快。

    但是,我以后需要访问这些元素,所以我也倾向于单独构建它们,然后附加它们,这样我就可以缓存它们,而不是在附加所有HTML之后选择它们。

    例如。:

    var html = $('<div id="container">.....several more divs, anchors and inputs all with IDs......</div>');
    
    <dom element>.append(html);
    this.container = $('#container');
    this.search = $('#search');
    ...and so on
    

    this.container = $('<div id="container"></div>');
    this.search = $('<input .... id="search" />');
    ...and the rest of the divs, anchors and inputs then...
    
    <dom element>.append(this.container).append(this.search) ..... and so on
    
    2 回复  |  直到 16 年前
        2
  •  0
  •   PetersenDidIt    16 年前

    var html = $('<div id="container">.....several more divs, anchors and inputs all with IDs......</div>');
    

    通过为选择器提供您知道元素所在的有限上下文,可以加快选择器的速度。

    this.container = html; //since #container is the top div in html, html = #container
    this.search = html.find('#search');
    

    然后最后添加到DOM中 这是一个缓慢的追加,因为它会导致浏览器重新绘制。

    <dom element>.append(html);