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

jquery find与id属性

  •  0
  • Raphael  · 技术社区  · 7 年前

    目前,我正在寻找访问元素的最快方法。

    更快的是:

    $('body').find('#elemID');
    

    VS

    var id = $('#elemID');
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   ouni    7 年前

    Document.getElementById() 是最快的,不需要jquery。然后,您可以选择使用 $ ,如果需要jquery功能。

        2
  •  1
  •   Joe Warner    7 年前

    快速回答是,这并不重要,但如果你必须选择除第一个以外的任何一个。

    如果您担心性能问题,请寻找瓶颈,而不是微观优化。

    如果可能的话,尽量使用普通的JS,但是如果您使用的是jquery,那么最好从中得到最大的好处。

    const body = () => $('body').find('#elemID');
    const id = () => $('#elemID');
    
    const idJs = () => document.getElementById('elemID');
    
    function performanceCalc(fn, params) {
        const start = new Date()
        const result = fn()
        const end = new Date()
    
        console.log(`Result: ${result} ${params}. Execution Time: ${end - start} ms`)
    }
    
    performanceCalc(body, 'body')
    
    performanceCalc(id, 'id')
    
    performanceCalc(idJs, 'idJs')
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="elemID"></div>