Skip to content

Latest commit

 

History

History
55 lines (39 loc) · 753 Bytes

File metadata and controls

55 lines (39 loc) · 753 Bytes

jQuery最佳实践

  • 使用 $ 作为jQuery对象变量名的前缀。
// bad
const sidebar = $('.sidebar');

// good
const $sidebar = $('.sidebar');
  • 缓存 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'
    });
}
  • 尽量使用jQueryfind方法来获取DOM
// bad
$('ul', '.sidebar').hide();


// good
$('.sidebar ul').hide();

// good
$('.sidebar > ul').hide();

// good
$sidebar.find('ul').hide();