25. jQuery

2018-02-24 16:11 更新
  • 25.1?使用?$?作為存儲(chǔ) jQuery 對(duì)象的變量名前綴。

    // bad
    const sidebar = $('.sidebar');
    
    // good
    const $sidebar = $('.sidebar');
  • 25.2?緩存 jQuery 查詢。

    // bad
    function setSidebar() {
      $('.sidebar').hide();
    
      // ...stuff...
    
      $('.sidebar').css({
        'background-color': 'pink'
      });
    }
    
    // good
    function setSidebar() {
      const $sidebar = $('.sidebar');
      $sidebar.hide();
    
      // ...stuff...
    
      $sidebar.css({
        'background-color': 'pink'
      });
    }
  • 25.3?對(duì) DOM 查詢使用層疊?$('.sidebar ul')?或 父元素 > 子元素?$('.sidebar > ul')。?jsPerf

  • 25.4?對(duì)有作用域的 jQuery 對(duì)象查詢使用?find。

    // bad
    $('ul', '.sidebar').hide();
    
    // bad
    $('.sidebar').find('ul').hide();
    
    // good
    $('.sidebar ul').hide();
    
    // good
    $('.sidebar > ul').hide();
    
    // good
    $sidebar.find('ul').hide();
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)