js代碼規(guī)范


/**
 * 數(shù)值類型
 */
// 原始值類型 string number boolean null undefined
var foo = 1;
var bar = foo;

bar = 9;
console.log(foo,bar);

// 非原始值類型 object array function

var foo = [1,2];
var bar = foo;
bar[0] = 9;

console.log(foo[0],bar[0]);

/**
 * 對(duì)象
 */

// 對(duì)象 使用字面量創(chuàng)建對(duì)象

var item = new Object();//bad
var item = {};//good

// 不要使用保留字作為鍵名 他們?cè)贗E8下不工作

// bad
var superman = {
    default:{clark:'kent'},
    private:true
};
// good
var superman = {
    defaults:{clark:'kent'},
    hidden:true
};

// 使用同義詞替換需要使用的保留字
// bad
var superman = {
    class:'alien'
};
// bad
var superman = {
    kclass:'alien'
};
// good
var superman = {
    type:'alien'
}

/**
 * 數(shù)組
 */

// 使用字面量創(chuàng)建數(shù)組

var items = new Array();//bad
var items = [];//good

// 向數(shù)組添加元素時(shí)使用push來(lái)替代直接賦值
var someStack = [];
someStack[someStack.length] = 'abcdefbaba';//dad
someStack.push('abcdefbaba');//good

//當(dāng)你需要拷貝數(shù)組時(shí)苍息,使用slice
var len = items.length;
var itemsCopy = [];
var i;

//bad
for (i = 0;i < len;i++) {
    itemsCopy[i] = items[i];
}

// good
itemsCopy = items.slice();

// 使用slice將類數(shù)組對(duì)象轉(zhuǎn)換為數(shù)組
function trigger() {
    var args = Array.prototype.slice.call(arguments);
    // ...
}

/**
 * 字符串
 */

//  使用單引號(hào)包裹字符串

var name = "Bob Parr";//bad
var name = 'Bob Parr';//good;
var fullName = "Bob" + this.lastName;//bad
var fullName = 'Bob' + this.lastName;//good

// 超過(guò)100個(gè)字符的字符串應(yīng)該使用連詞符寫成多行型凳。
// 通過(guò)過(guò)度使用柿顶,通過(guò)連詞符鏈接的長(zhǎng)度可能會(huì)影響性能

// bad
var errorMessage = 'This is a super long error that was thrown beacause of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.'

// bad
var errorMessage = 'This is a super long error that was thrown because \
of Batman. When you stop to think about how Batman had anything to do \
with this, you would get nowhere \
fast.';

// good
var errorMessage = 'This is a super long error that was thrown because' + 
'of Batman. When you stop to think about how Batman had anything to do' +
'with this, you would get nowhere fast.';

// 程序化生成的字符串使用join鏈接而不是使用連接符,尤其是IE下

var items;
var messages;
var length;
var i;

messages = [{
    state:'success',
    message:'This one wroked'
},{
    state:'suceess',
    message:'This one worked as well'
},{
    state:'error',
    message:'This one did not work'
}];

length = messages.length;

//bad
function inbox(message) {
    items = '<ul>';

    for (i = 0;i<length;i++){
        items += '<li>' + messages[i].message + '</li>'
    }
    return items + '</ul>';
}

// good
function inbox(messages) {
    items = [];
    for(i = 0;i<length;i++){
        items[i] = '<li>' + messages[i].message + '</li>';
    }
    return '<ul>' + items.join('') + '</ul>';
}

/**
 * 函數(shù)
 */

//  函數(shù)表達(dá)式

// 匿名函數(shù)表達(dá)式
var annoymous = function(){
    return true;
};
// 命名函數(shù)表達(dá)式
var named = function named() {
    return true;
};
// 立即調(diào)用的函數(shù)表達(dá)式IIFE
(function(){
console.log('Welcome to the Internet. Please follow me.');
}());

// 永遠(yuǎn)不要在一個(gè)非函數(shù)代碼塊if while 等 中聲明一個(gè)函數(shù)旨别,瀏覽器允許你這么做,但它們的解析表現(xiàn)不一致,正確的做法是在塊兒外定義一個(gè)變量碉渡,然后將函數(shù)賦值給它乍恐。

// ECMA-262 把塊定義為一組語(yǔ)句评疗。函數(shù)聲明不是語(yǔ)句。

// bad
if (currentUser){
    function test () {
        console.log('Nope.');
    }
}
// good
var test;
if (currentUser) {
    test = function test(){
        console.log('Yup.');
    };
}

// 永遠(yuǎn)不要把參數(shù)命名為arguments 這將取代函數(shù)作用域內(nèi)的 arguments 對(duì)象
// bad
 function nope(name,options,arguments) {
     // ...stuff
 }

//  good
function yup(name,options,args){
    // ...stuff...
}

/**
 * 屬性
 */

// 使用.來(lái)訪問(wèn)對(duì)象的屬性

var luke = {
    jedi:true,
    age:28
};

//bad
var isJedi = luke['jedi'];
// good
var isJedi = luke.jedi;

// 當(dāng)通過(guò)變量訪問(wèn)屬性時(shí)使用中括號(hào)

function getProp(prop){
    return luke[prop];
}

var isJedi = getProp('jedi');

/**
 * 變量
 */

//  總是使用 var 來(lái)聲明變量茵烈。不這么做將會(huì)導(dǎo)致產(chǎn)生全局變量百匆。我們要避免污染全局命名空間。
//bad
superPower = new SuperPower();
//good
var superPower = new SuperPower();

// 使用var 聲明每一個(gè) 變量呜投。 這樣做的好處是增加變量將變得更加容易加匈。而且你永遠(yuǎn)不用再擔(dān)心調(diào)換錯(cuò);和仑荐,
//bad
var items = getItems(),
    goSportsItem = true,
    dragonball = 'z';
//bad
// (跟上面的代碼比較一下雕拼,看看哪里錯(cuò)了)
var items = getItems(),
goSportsItem = true;
dragonball = 'z';

// good
var items = getItems(),
var goSportsItem = true;
var dragonball = 'z';

// 最后在聲明未賦值的變量。當(dāng)你需要引用前面的變量賦值時(shí)粘招,這將變得很有用啥寇。

// bad
var i,len,dragonball,
    item = getItems(),
    goSportsTeam = true;
// bad
var i;
var items = getItems();
var dragonball;
var goSportsItem = true;
var len;

// good
var items = getItems();
var goSportsItem = true;
var dragonball;
var length;
var i;

// 在作用域頂部聲明變量,這將幫你避免聲明變量提升的相關(guān)問(wèn)題
//bad
function lalala (){
    test();
    console.log('doing stuff...');
    // ...other stuff
    var name = getName();
    if (name === 'test'){
        return false;
    }
    return name;
}
// good
function lalala (){
    var name = getName();
    test();
    console.log('doing stuff...');
    // ...other stuff...
    if (name === 'test') {
        return false;
    }
}
// bad - 不必要的函數(shù)調(diào)用
function lalala(){
    var name = getName();
    if (!arguments.length) {
        return false;
    }
    this.setFirstName(name);
    return true;
}

// good
function lalala(){
    var name;
    if (!arguments.length) {
        return false;
    }
    name = getName();
    this.setFirstName(name);

    return true;
}

/**
 * 提升
 */

// 變量提升會(huì)提升至作用域頂部,但賦值不會(huì)

// 我們知道這樣不能正常工作(假設(shè)這里沒(méi)有名為 notDefined 的全局變量)
function example() {
    console.log(notDefined); // => throws a ReferenceError
  }
  
  // 但由于變量聲明提升的原因辑甜,在一個(gè)變量引用后再創(chuàng)建它的變量聲明將可以正常工作甜橱。
  // 注:變量賦值為 `true` 不會(huì)提升厨钻。
  function example() {
    console.log(declaredButNotAssigned); // => undefined
    var declaredButNotAssigned = true;
  }
  
  // 解釋器會(huì)把變量聲明提升到作用域頂部进肯,意味著我們的例子將被重寫成:
  function example() {
    var declaredButNotAssigned;
    console.log(declaredButNotAssigned); // => undefined
    declaredButNotAssigned = true;
  }

//   匿名函數(shù)表達(dá)式會(huì)提升它們的變量名,但不會(huì)提升函數(shù)的賦值友存。
  
  function example() {
    console.log(anonymous); // => undefined
  
    anonymous(); // => TypeError anonymous is not a function
  
    var anonymous = function () {
      console.log('anonymous function expression');
    };
  }

//   函數(shù)聲明提升它們的名字和函數(shù)體子檀。
  
  function example() {
    superPower(); // => Flying
  
    function superPower() {
      console.log('Flying');
    }
  }

/**
* 比較運(yùn)算符 & 等號(hào)
*/

// 優(yōu)先使用 === 和 镊掖!== 而不是 == 和 !=

// 條件表達(dá)式例如 if 語(yǔ)句 通過(guò)抽象方法 ToBoolean 強(qiáng)制計(jì)算它們的表達(dá)式并總是遵循下面的規(guī)則:
// 對(duì)象被計(jì)算為true
// undefined被計(jì)算為 false
// Null 被計(jì)算為false
// 布爾值被計(jì)算為布爾的值
// 數(shù)字 如果是 +0 -0 或者 NaN 被計(jì)算為 false 否則為true
// 字符串 如果是空字符串''被計(jì)算為false 否則為true

if ([0]) {
    //true 一個(gè)數(shù)組就是一個(gè)對(duì)象,對(duì)象被計(jì)算為true
}

// 使用快捷方式
// bad
if (name != '') {
    //...stuff...
}
// good
if (name) {
    //...stuff
}
// bad
if (collection.length > 0) {
    //...stuff...
}
// good
if (collection.length) {
    //...stuff...
}

/**
 * 塊
 */
// 使用大括號(hào)包括的多行代碼塊
// bad
if (test) 
    return false;

// good
if (test) return false;
// good
if (test) {
    return false;
}

// bad
function test() {return false};
// good
function test(){
    return false;
}

// 如果通過(guò) if 和 else 使用多行代碼塊褂痰,把else 放在if代碼塊 關(guān)閉括號(hào)的同一行亩进。
// bad
if (test) {
    thing1();
    thing2();
}
else{
    thing3();
}
// good
if (test) {
    thing1();
    thing2();
}else {
    thing3();
}

/**
 * 注釋
 */
// bad
// make() returns a new element
// based on the passed in tag name
//
// @param {String} tag
// @return {Element} element
function make(tag) {
    // ...stuff...
    return element;
}

/**
 * make() returns a new element
 * based on the passed in tah name
 * 
 * @param {String} tag 
 * @return {Element} elment
 */
function make(tag) {
    
      // ...stuff...
    
      return element;
}

// 使用//作為單行注釋,在評(píng)論對(duì)象上面另起一行使用單行注釋缩歪。在注釋前插入空行
// bad
var active = ture;//is current tab

// good
// is current tab
var active = ture;

// bad
function getType() {
    console.log('fetching type...');
    // set the default type to 'no type'
    var type = this.type || 'no type';
    return type;
}

// good 在注釋前插入空行
function getType() {
    console.log('fetching type...');

    // set the defalut type to 'no type'
    var type = this.type || 'no type';
    return type;
}

// 給注釋增加FIXME 或 TODO 的前綴可以幫助其他開(kāi)發(fā)者快速了解這是一個(gè)需要復(fù)查的問(wèn)題
// 或是給要實(shí)現(xiàn)的功能提供一個(gè)解決方案归薛。這有別于常見(jiàn)注釋,因?yàn)樗麄兪强刹僮鞯摹?// 使用 FIXME -- need to figure this out 或者 TODO -- need to implement

function Calculator() {
    // FIXME: shouldn't use a global here
    total = 0;

    return this;
}

function Calculator(){

    // TODO: total should be configurable by an options pamr
    this.total = 0;

    return this;
}

/**
 * 空白
 */

//  使用2個(gè)空格作為縮進(jìn)
// bad
function test() {
    var name;
}
// bad
function test() {
 var name;
}
// good
function test() {
  var name;
}

// 在打括號(hào)前放一個(gè)空格

// bad
function test(){
    console.log('test');
}
// good
function test() {
    console.log('test');
}
// bad
dog.set('attr',{
    age: '1 year',
    breed: 'Benrnese Mountain Dog'
});
// good
dog.set('attr', {
    age: '1 year',
    breed: 'Benrnese Mountain Dog'
});

// 在控制語(yǔ)句 if while 等 的小括號(hào)前放一個(gè)空格匪蝙。在函數(shù)調(diào)用及聲明中主籍,不在函數(shù)的參數(shù)列表前加空格

// bad
if(isJedi) {
  fight ();  
}

// good
if (isJedi) {
    fight();
}

// bad
function fight () {
    console.log ('Swooosh!');
}

// good
function fight() {
    console.log ('Swooosh!');
}

// 使用空格把運(yùn)算符隔開(kāi)

// bad
var x=y+5;


// good
var x = y + 5;

// 在文件末尾插入一個(gè)空行

// bad
(function (global) {
    // ...stuff...
})(this);
// bad
(function (global) {
   // ...stuff...
})(this);?
?
// good
(function (global) {
     // ...stuff...
})(this);?

// 在使用長(zhǎng)方法鏈時(shí)進(jìn)行縮進(jìn)。使用前面的點(diǎn) . 強(qiáng)調(diào)這是方法調(diào)用而不是新語(yǔ)句逛球。
// bad
$('#items').find('.selected').highlight().end().find('.open').updateCount();

// bad
$('#items').
  find('.selected').
    highlight().
    end().
  find('.open').
    updateCount();

// good
$('#items')
  .find('.selected')
    .highlight()
    .end()
  .find('.open')
    .updateCount();

// bad
var leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true)
    .attr('width', (radius + margin) * 2).append('svg:g')
    .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
    .call(tron.led);

// good
var leds = stage.selectAll('.led')
    .data(data)
  .enter().append('svg:svg')
    .classed('led', true)
    .attr('width', (radius + margin) * 2)
  .append('svg:g')
    .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
    .call(tron.led);

// 在塊末和新語(yǔ)句前插入空行千元。

// bad
if (foo) {
    return bar;
  }
  return baz;
  
  // good
  if (foo) {
    return bar;
  }
  
  return baz;
  
  // bad
  var obj = {
    foo: function () {
    },
    bar: function () {
    }
  };
  return obj;
  
  // good
  var obj = {
    foo: function () {
    },
  
    bar: function () {
    }
  };
  
  return obj;

// 逗號(hào)
// 行首逗號(hào) 不需要 
// bad
var story = [
    once
  , upon
  , aTime
];

// good
var story = [
  once,
  upon,
  aTime
];

// bad
var hero = {
    firstName: 'Bob'
  , lastName: 'Parr'
  , heroName: 'Mr. Incredible'
  , superPower: 'strength'
};

// good
var hero = {
  firstName: 'Bob',
  lastName: 'Parr',
  heroName: 'Mr. Incredible',
  superPower: 'strength'
};

// 額外的行末逗號(hào)不需要
// bad
var hero = {
    firstName: 'Kevin',
    lastName: 'Flynn',
  };
  
  var heroes = [
    'Batman',
    'Superman',
  ];
  
  // good
  var hero = {
    firstName: 'Kevin',
    lastName: 'Flynn'
  };
  
  var heroes = [
    'Batman',
    'Superman'
  ];

//   使用分號(hào)
// bad
(function () {
    var name = 'Skywalker'
    return name
  })()
  
  // good
  (function () {
    var name = 'Skywalker';
    return name;
  })();
  
  // good (防止函數(shù)在兩個(gè) IIFE 合并時(shí)被當(dāng)成一個(gè)參數(shù)
  ;(function () {
    var name = 'Skywalker';
    return name;
  })();

//   類型轉(zhuǎn)換
// 在語(yǔ)句開(kāi)始時(shí)執(zhí)行類型轉(zhuǎn)換

// 字符串
this.reviewScore = 9;
// bad
var totalScore = this.reviewScore + '';
// good
var totalScore = '' + this.reviewScore;

// bad
var totalScore = '' + this.reviewScore + 'total score';

// good
var totalScore = this.reviewScore + 'total score';

// 使用 parseInt 轉(zhuǎn)換數(shù)字時(shí)總是帶上類型轉(zhuǎn)換的基數(shù)
var inputValue = '4';
// bad
var val = new Number(inputValue);
// bad
var val = +inputValue;
// bad
var val = inputValue >> 0;
// bad
var val = parseInt(inputValue);

// good
var val = Number(inputValue);
// good
var val = parseInt(inputValue,10);

// 如果因?yàn)槟承┰?parseInt 成為你所做的事的瓶頸而需要使用位操作解決性能問(wèn)題時(shí),留個(gè)注釋說(shuō)清楚原因和你的目的颤绕。
// good
/**
 * parseInt was the reason my code was slow.
 * Bitshifting the String to coerce it to a
 * Number made it a lot faster.
 */
var val = inputValue >> 0;
// 注: 小心使用位操作運(yùn)算符幸海。數(shù)字會(huì)被當(dāng)成 64 位值,但是位操作運(yùn)算符總是返回 32 位的整數(shù)(source)奥务。位操作處理大于 32 位的整數(shù)值時(shí)還會(huì)導(dǎo)致意料之外的行為物独。討論。最大的 32 位整數(shù)是 2,147,483,647:

// 布爾
var age = 0;

// bad
var hasAge = new Boolean(age);

// good
var hasAge = Boolean(age);

// good
var hasAge = !!age;

// 命名規(guī)則
// 避免單字母命名氯葬,命名應(yīng)具有描述性

// bad
function q() {
    // ...stuff
}
// good
function query() {
    // ..stuff..
}

// 使用駝峰式命名對(duì)象挡篓、函數(shù)和實(shí)例

// bad
var OBJEcttsssss = {};
var this_is_my_object = {};
var o = {};
function c() {}

// good
var thisIsMyObject = {};
function thisIsMyFunction() {}

// 使用帕斯卡式命名構(gòu)造函數(shù)或類。

// bad
function user(options) {
    this.name = options.name;
  }
  
  var bad = new user({
    name: 'nope'
  });
  
  // good
  function User(options) {
    this.name = options.name;
  }
  
  var good = new User({
    name: 'yup'
  });

  // bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
this._firstName = 'Panda';

// good
this.firstName = 'Panda';

// 不要保存 this 的引用溢谤。使用 Function#bind瞻凤。

// bad
function test() {
    var self = this;
    return function(){
        console.log(self);
    };
}

// bad
function test() {
    var that = this;
    return function () {
      console.log(that);  
    };
}
// bad
function test() {
    var _this = this;
    return function () {
        console.log(_this);
    };
}

// good
function test() {
    return function(){
     console.log(this);
    }.bind(this);
}

// 給函數(shù)命名,這在做堆棧時(shí)很有幫助
// bad
var log = function (msg) {
    console.log(msg);
};
// good
var log = function log(msg) {
    console.log(msg);
};

// 如果你的一個(gè)文件導(dǎo)出一個(gè)類世杀,你的文件名應(yīng)該與類名完全相同
// file contents
class CheckBox {
    // ...
  }
  module.exports = CheckBox;
  
  // in some other file
  // bad
  var CheckBox = require('./checkBox');
  
  // bad
  var CheckBox = require('./check_box');
  
  // good
  var CheckBox = require('./CheckBox');

  /**
   * 存取器
   */
//   屬性的存取函數(shù)不是必須的阀参。
// 如果你需要存取函數(shù)時(shí)使用 getVal() 和 setVal('hello')。

// bad
dragon.age();

// good
dragon.getAge();

// bad
dragon.age(25);

// good
dragon.setAge(25);

// 如果屬性是布爾值瞻坝,使用 isVal() 或 hasVal()蛛壳。
// bad
if (!dragon.age()) {
    return false;
  }
  
  // good
  if (!dragon.hasAge()) {
    return false;
  }
//   創(chuàng)建 get() 和 set() 函數(shù)是可以的杏瞻,但要保持一致。
function Jedi(options) {
    options || (options = {});
    var lightsaber = options.lightsaber || 'blue';
    this.set('lightsaber', lightsaber);
  }
  
  Jedi.prototype.set = function set(key, val) {
    this[key] = val;
  };
  
  Jedi.prototype.get = function get(key) {
    return this[key];
  };

/**
 * 構(gòu)造函數(shù)
 */
// 給對(duì)象原型分配方法衙荐,而不是使用一個(gè)新的對(duì)象覆蓋原型捞挥,覆蓋原型將導(dǎo)致繼承出現(xiàn)問(wèn)題:重設(shè)原型將覆蓋原有原型!

function Jedi() {
    console.log('new jedi');
}

// bad
Jedi.prototype = {
    fight: function fight() {
      console.log('fighting');
    },
  
    block: function block() {
      console.log('blocking');
    }
  };

// good
Jedi.prototype.fight = function fight() {
    console.log('fighting');
  };
  
  Jedi.prototype.block = function block() {
    console.log('blocking');
  };

//   方法可以返回 this 來(lái)實(shí)現(xiàn)方法鏈?zhǔn)绞褂谩?// bad
Jedi.prototype.jump = function jump() {
    this.jumping = true;
    return true;
};

Jedi.prototype.setHeight = function setHeight(height) {
    this.height = height;
};

var luke = new Jedi();
luke.jump();//=>true
luke.setHeight(20);//=>undefined

// good
Jedi.prototype.jump = function jump() {
    this.jumping = true;
    return this;
}

Jedi.prototype.setHeight = function setHeight(height) {
    this.height = height;
    return this;
};

var luke = new Jedi();

luke.jump()
    .setHeight(20);

// 寫一個(gè)自定義的 toString() 方法是可以的忧吟,但是確保它可以正常工作且不會(huì)產(chǎn)生副作用砌函。

function Jedi(options) {
    options || (options = {});
    this.name = options.name || 'no name';
}

Jedi.prototype.getName = function getName() {
    return this.name;
};

Jedi.prototype.toString = function() {
    return 'Jedi -' + this.getName();
};

/**
 * 事件
 */

// 當(dāng)給事件附加數(shù)據(jù)時(shí)(無(wú)論是 DOM 事件還是私有事件),傳入一個(gè)哈希而不是原始值溜族。
// 這樣可以讓后面的貢獻(xiàn)者增加更多數(shù)據(jù)到事件數(shù)據(jù)而無(wú)需找出并更新事件的每一個(gè)處理器讹俊。例如,不好的寫法:

// bad
$(this).trigger('listingUpdated', listing.id);

// bad
$(this).trigger('listingUpdated', listing.id);


$(this).on('listingUpdated', function (e, listingId) {
  // do something with listingId
});


// 更好的寫法:
// good
$(this).trigger('listingUpdated', { listingId : listing.id });


$(this).on('listingUpdated', function (e, data) {
  // do something with data.listingId
});

/**
 * 模塊
 */
// 模塊應(yīng)該以 ! 開(kāi)始煌抒。這樣確保了當(dāng)一個(gè)不好的模塊忘記包含最后的分號(hào)時(shí)仍劈,在合并代碼到生產(chǎn)環(huán)境后不會(huì)產(chǎn)生錯(cuò)誤。詳細(xì)說(shuō)明

// 文件應(yīng)該以駝峰式命名寡壮,并放在同名的文件夾里贩疙,且與導(dǎo)出的名字一致。

// 增加一個(gè)名為 noConflict() 的方法來(lái)設(shè)置導(dǎo)出的模塊為前一個(gè)版本并返回它况既。

// 永遠(yuǎn)在模塊頂部聲明 'use strict';这溅。

// fancyInput/fancyInput.js

!function (global) {
    'use strict';
  
    var previousFancyInput = global.FancyInput;
  
    function FancyInput(options) {
      this.options = options || {};
    }
  
    FancyInput.noConflict = function noConflict() {
      global.FancyInput = previousFancyInput;
      return FancyInput;
    };
  
    global.FancyInput = FancyInput;
  }(this);

  /**
   * jQuery
   */
//   使用 $ 作為存儲(chǔ) jQuery 對(duì)象的變量名前綴。
// bad
var sidebar = $('.sidebar');

// good
var $sidebar = $('.sidebar');

// 緩存 jQuery 查詢坏挠。
// bad
function setSidebar() {
    $('.sidebar').hide();
  
    // ...stuff...
  
    $('.sidebar').css({
      'background-color': 'pink'
    });
  }
  
  // good
  function setSidebar() {
    var $sidebar = $('.sidebar');
    $sidebar.hide();
  
    // ...stuff...
  
    $sidebar.css({
      'background-color': 'pink'
    });
  }
//   對(duì) DOM 查詢使用層疊 $('.sidebar ul') 或 父元素 > 子元素 $('.sidebar > ul')芍躏。 jsPerf
// 對(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();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末降狠,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子庇楞,更是在濱河造成了極大的恐慌榜配,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件吕晌,死亡現(xiàn)場(chǎng)離奇詭異蛋褥,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)睛驳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門烙心,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人乏沸,你說(shuō)我怎么就攤上這事淫茵。” “怎么了蹬跃?”我有些...
    開(kāi)封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵匙瘪,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng)丹喻,這世上最難降的妖魔是什么薄货? 我笑而不...
    開(kāi)封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮碍论,結(jié)果婚禮上谅猾,老公的妹妹穿的比我還像新娘。我一直安慰自己鳍悠,他們只是感情好赊瞬,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著贼涩,像睡著了一般巧涧。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上遥倦,一...
    開(kāi)封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天谤绳,我揣著相機(jī)與錄音,去河邊找鬼袒哥。 笑死缩筛,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的堡称。 我是一名探鬼主播瞎抛,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼却紧!你這毒婦竟也來(lái)了桐臊?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤晓殊,失蹤者是張志新(化名)和其女友劉穎断凶,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體巫俺,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡认烁,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了介汹。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片却嗡。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖嘹承,靈堂內(nèi)的尸體忽然破棺而出窗价,到底是詐尸還是另有隱情,我是刑警寧澤赶撰,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布舌镶,位于F島的核電站柱彻,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏餐胀。R本人自食惡果不足惜哟楷,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望否灾。 院中可真熱鬧卖擅,春花似錦、人聲如沸墨技。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)扣汪。三九已至断楷,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間崭别,已是汗流浹背冬筒。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留茅主,地道東北人舞痰。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像诀姚,于是被迫代替她去往敵國(guó)和親响牛。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容