实用的JavaScript技巧、窍门和最佳实践

1 – 在第一次给一个变量赋值的时候不要忘记使用var关键字javascript

给一个未定义的变量赋值会致使建立一个全局变量。要避免全局变量。php

2 – 使用===,而不是==css

==(或!=)操做符在须要的时候会自动执行类型转换。===(或!==)操做不会执行任何转换。它将比较值和类型,并且在速度上也被认为优于==。html

1
2
3
4
5
6
7
8
[ 10 ] === 10    // is false
[ 10 ]  == 10    // is true
'10' == 10     // is true
'10' === 10    // is false
  []   == 0     // is true
  [] ===  0     // is false
  '' == false   // is true but true == "a" is false
  '' ===   false // is false

3 – 使用闭包实现私有变量(译者添加)前端

1
2
3
4
5
6
7
8
9
10
11
12
function Person(name, age) {
     this .getName = function () { return name; };
     this .setName = function (newName) { name = newName; };
     this .getAge = function () { return age; };
     this .setAge = function (newAge) { age = newAge; };
 
     //未在构造函数中初始化的属性
     var occupation;
     this .getOccupation = function () { return occupation; };
     this .setOccupation = function (newOcc) { occupation =
                          newOcc; };
}

4 – 在语句结尾处使用分号html5

在语句结尾处使用分号是一个很好的实践。若是你忘记写了你也不会被警告,由于多数状况下JavaScript解释器会帮你加上分号。java

5 – 建立对象的构造函数web

1
2
3
4
5
6
function Person(firstName, lastName){
     this .firstName =  firstName;
     this .lastName = lastName;
}
 
var Saad = new Person( "Saad" , "Mousliki" );

6 – 当心使用typeof、instanceof和constructorchrome

1
2
3
4
var arr = [ "a" , "b" , "c" ];
typeof arr;   // return "object"
arr  instanceof Array // true
arr.constructor();  //[]

7 – 建立一个自调用函数(Self-calling Funtion)数组

这个常常被称为自调用匿名函数(Self-Invoked Anonymous Function)或者即时调用函数表达式(IIFE-Immediately Invoked Function Expression)。这是一个在建立后当即自动执行的函数,一般以下:

1
2
3
4
5
6
7
( function (){
     // some private code that will be executed automatically
})();
( function (a,b){
     var result = a+b;
     return result;
})( 10 , 20 )

8- 从数组中获取一个随机项

1
2
3
var items = [ 12 , 548 , 'a' , 2 , 5478 , 'foo' , 8852 , , 'Doe' , 2145 , 119 ];
 
var  randomItem = items[Math.floor(Math.random() * items.length)];

9 – 在特定范围内获取一个随机数

这个代码片断在你想要生成测试数据的时候很是有用,好比一个在最小最大值之间的一个随机薪水值。

1
var x = Math.floor(Math.random() * (max - min + 1 )) + min;

10 – 在0和设定的最大值之间生成一个数字数组

1
2
3
var numbersArray = [] , max = 100 ;
 
for ( var i= 1 ; numbersArray.push(i++) < max;);  // numbers = [0,1,2,3 ... 100]

11 – 生成一个随机的数字字母字符串

1
2
3
4
5
function generateRandomAlphaNum(len) {
     var rdmstring = "" ;
     for ( ; rdmString.length &lt; len; rdmString  += Math.random().toString( 36 ).substr( 2 ));
     return  rdmString.substr( 0 , len);
}

【译者注:特地查了一下Math.random()生成0到1之间的随机数,number.toString(36)是将这个数字转换成36进制(0-9,a-z),最后substr去掉前面的“0.”字符串】

12 – 打乱一个数字数组

1
2
3
var numbers = [ 5 , 458 , 120 , - 215 , 228 , 400 , 122205 , - 85411 ];
numbers = numbers.sort( function (){ return Math.random() - 0.5 });
/* the array numbers will be equal for example to [120, 5, 228, -215, 400, 458, -85411, 122205]  */

13 – String的trim函数

在Java、C#、PHP和不少其余语言中都有一个经典的 trim 函数,用来去除字符串中的空格符,而在JavaScript中并无,因此咱们须要在String对象上加上这个函数。

1
String .prototype.trim = function (){ return this .replace(/^\s+|\s+$/g, "" );};

【译者注:去掉字符串的先后空格,不包括字符串内部空格】

14 – 附加(append)一个数组到另外一个数组上

1
2
3
4
5
var array1 = [ 12 , "foo" , {name: "Joe" } , - 2458 ];
 
var array2 = [ "Doe" , 555 , 100 ];
Array .prototype.push.apply(array1, array2);
/* array1 will be equal to  [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */

【译者注:其实concat能够直接实现两个数组的链接,可是它的返回值是一个新的数组。这里是直接改变array1】

15 – 将arguments对象转换成一个数组

1
var argArray = Array .prototype.slice.call(arguments);

【译者注:arguments对象是一个类数组对象,但不是一个真正的数组

16 – 验证参数是不是数字(number)

1
2
3
function isNumber(n){
     return ! isNaN ( parseFloat (n)) && isFinite (n);
}

17 – 验证参数是不是数组

1
2
3
function isArray(obj){
     return Object .prototype.toString.call(obj) === '[object Array]' ;
}

注意:若是toString()方法被重写了(overridden),你使用这个技巧就不能获得想要的结果了。或者你可使用:

1
Array .isArray(obj); // 这是一个新的array的方法

若是你不在使用多重frames的状况下,你还可使用 instanceof 方法。但若是你有多个上下文,你就会获得错误的结果。

1
2
3
4
5
6
7
8
9
var myFrame = document.createElement( 'iframe' );
document.body.appendChild(myFrame);
 
var myArray = window.frames[window.frames.length- 1 ]. Array ;
var arr = new myArray(a,b, 10 ); // [a,b,10]
 
// instanceof will not work correctly, myArray loses his constructor
// constructor is not shared between frames
arr instanceof Array ; // false

【译者注:关于如何判断数组网上有很多讨论,你们能够google一下。这篇就写的挺详细的。】

18 – 获取一个数字数组中的最大值或最小值

1
2
3
var  numbers = [ 5 , 458 , 120 , - 215 , 228 , 400 , 122205 , - 85411 ];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);

【译者注:这里使用了Function.prototype.apply方法传递参数的技巧】

19 – 清空一个数组

1
2
var myArray = [ 12 , 222 , 1000 ];
myArray.length = 0 ; // myArray will be equal to [].

20 – 不要使用 delete 来删除一个数组中的项。

使用 splice 而不要使用 delete 来删除数组中的某个项。使用 delete 只是用 undefined 来替换掉原有的项,并非真正的从数组中删除。

不要使用这种方式:

1
2
3
4
5
var items = [ 12 , 548 , 'a' , 2 , 5478 , 'foo' , 8852 , , 'Doe' , 2154 , 119 ];
items.length; // return 11
delete items[ 3 ]; // return true
items.length; // return 11
/* items will be equal to [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154,       119]   */

而使用:

1
2
3
4
5
var items = [ 12 , 548 , 'a' , 2 , 5478 , 'foo' , 8852 , , 'Doe' , 2154 , 119 ];
items.length; // return 11
items.splice( 3 , 1 ) ;
items.length; // return 10
/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154,       119]   */

delete 方法应该被用来删除一个对象的某个属性。

21 – 使用 length 来截短一个数组

跟上面的清空数组的方式相似,咱们使用 length 属性来截短一个数组。

1
2
var myArray = [ 12 , 222 , 1000 , 124 , 98 , 10 ];
myArray.length = 4 ; // myArray will be equal to [12 , 222 , 1000 , 124].

此外,若是你将一个数组的 length 设置成一个比如今大的值,那么这个数组的长度就会被改变,会增长新的 undefined 的项补上。 数组的 length 不是一个只读属性。

1
2
myArray.length = 10 ; // the new array length is 10
myArray[myArray.length - 1 ] ; // undefined

22 – 使用逻辑 AND/OR (更多)作条件判断

1
2
3
var foo = 10 ;
foo == 10 && doSomething(); // 等价于 if (foo == 10) doSomething();
foo == 5 || doSomething(); // 等价于 if (foo != 5) doSomething();

逻辑 AND 还能够被使用来为函数参数设置默认值

1
2
3
function doSomething(arg1){
     Arg1 = arg1 || 10 ; // 若是arg1没有被设置的话,Arg1将被默认设成10
}

23 – 使用 map() 方法来遍历一个数组里的项

1
2
3
4
var squares = [ 1 , 2 , 3 , 4 ].map( function (val) {
     return val * val;
});
// squares will be equal to [1, 4, 9, 16]

24 – 四舍五入一个数字,保留N位小数

var num =2.443242342;
1.num = num.toFixed(4);  // num will be equal to 2.4432
2.num=Math.round(num * 10000) /10000

  

25 – 浮点数问题

1
2
3
0.1 + 0.2 === 0.3 // is false
9007199254740992 + 1 // is equal to 9007199254740992
9007199254740992 + 2 // is equal to 9007199254740994

为何会这样? 0.1+0.2等于0.30000000000000004。你要知道,全部的JavaScript数字在内部都是以64位二进制表示的浮点数,符合IEEE 754标准。更多的介绍,能够阅读这篇博文。你可使用 toFixed() 和 toPrecision() 方法解决这个问题。

26 – 使用for-in遍历一个对象内部属性(更多的时候注意检查属性

下面的代码片断可以避免在遍历一个对象属性的时候访问原型的属性

1
2
3
4
5
for ( var name in object) {
     if (object.hasOwnProperty(name)) {
         // do something with name
     }
}
注:向Array的原型中添加扩展方法后,当使用for-in循环数组时,这个扩展方法也会被循环出来。 譬如: 
Array.prototype.contain = function (obj) {
    return this.indexOf(obj) !== -1;
}
var arr = [1, 23, 45];
for (var i in arr) {
    console.log(i);
}
//输出:1 23 45  function (obj) { return this.indexOf(obj) !== -1; }

解决这个问题:

for (var i in arr) {
    if (arr.hasOwnProperty(i))
        console.log(i);
}

27 – 逗号操做符

1
2
3
4
var a = 0 ;
var b = ( a++, 99 );
console.log(a);  // a will be equal to 1
console.log(b);  // b is equal to 99

28 – 缓存须要计算和查询(calculation or querying)的变量

对于jQuery选择器,咱们最好缓存这些DOM元素。

1
2
3
4
var navright = document.querySelector( '#right' );
var navleft = document.querySelector( '#left' );
var navup = document.querySelector( '#up' );
var navdown = document.querySelector( '#down' );

29 – 在调用 isFinite()以前验证参数

1
2
3
4
5
6
7
isFinite ( 0 / 0 ) ; // false
isFinite ( "foo" ); // false
isFinite ( "10" ); // true
isFinite ( 10 );   // true
isFinite (undifined);  // false
isFinite ();   // false
isFinite ( null );  // true  !!!

30 – 避免数组中的负数索引(negative indexes)

1
2
3
var numbersArray = [ 1 , 2 , 3 , 4 , 5 ];
var from = numbersArray.indexOf( "foo" ) ;  // from is equal to -1
numbersArray.splice(from, 2 );    // will return [5]

确保调用 indexOf 时的参数不是负数。

31 – 基于JSON的序列化和反序列化(serialization and deserialization)

1
2
3
4
5
var person = {name : 'Saad' , age : 26 , department : {ID : 15 , name : "R&D" } };
var stringFromPerson = JSON.stringify(person);
/* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}"   */
var personFromString = JSON.parse(stringFromPerson);
/* personFromString is equal to person object  */

32 – 避免使用 eval() 和 Function 构造函数

使用 eval 和 Function 构造函数是很是昂贵的操做,由于每次他们都会调用脚本引擎将源代码转换成可执行代码。

1
2
var func1 = new Function(functionCode);
var func2 = eval(functionCode);

33 – 避免使用 with()

使用 with() 会插入一个全局变量。所以,同名的变量会被覆盖值而引发没必要要的麻烦。

34 – 避免使用 for-in 来遍历一个数组

避免使用这样的方式:

1
2
3
4
var sum = 0 ;
for ( var i in arrayNumbers) {
     sum += arrayNumbers[i];
}

更好的方式是:

1
2
3
4
var sum = 0 ;
for ( var i = 0 , len = arrayNumbers.length; i < len; i++) {
     sum += arrayNumbers[i];
}

附加的好处是,i 和 len 两个变量的取值都只执行了一次,会比下面的方式更高效:

1
for ( var i = 0 ; i < arrayNumbers.length; i++)

为何?由于arrayNumbers.length每次循环的时候都会被计算。

35 – 在调用 setTimeout() 和 setInterval() 的时候传入函数,而不是字符串。

若是你将字符串传递给 setTimeout() 或者 setInterval(),这个字符串将被如使用 eval 同样被解析,这个是很是耗时的。
不要使用:

1
2
setInterval( 'doSomethingPeriodically()' , 1000 );
setTimeOut( 'doSomethingAfterFiveSeconds()' , 5000 )

而用:

1
2
setInterval(doSomethingPeriodically, 1000 );
setTimeOut(doSomethingAfterFiveSeconds, 5000 );

36 – 使用 switch/case 语句,而不是一长串的 if/else

在判断状况大于2种的时候,使用 switch/case 更高效,并且更优雅(更易于组织代码)。但在判断的状况超过10种的时候不要使用 switch/case。
【译者注:查了一下文献,你们能够看一下这篇介绍

37 – 在判断数值范围时使用 switch/case

在下面的这种状况,使用 switch/case 判断数值范围的时候是合理的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function getCategory(age) {
     var category = "" ;
     switch ( true ) {
         case isNaN (age):
             category = "not an age" ;
             break ;
         case (age >= 50 ):
             category = "Old" ;
             break ;
         case (age <= 20 ):
             category = "Baby" ;
             break ;
         default :
             category = "Young" ;
             break ;
     };
     return category;
}
getCategory( 5 );  // will return "Baby"

【译者注:通常对于数值范围的判断,用 if/else 会比较合适。 switch/case 更适合对肯定数值的判断】

38 – 为建立的对象指定prototype对象

写一个函数来建立一个以指定参数做为prototype的对象是有可能:

1
2
3
4
5
6
function clone(object) {
     function OneShotConstructor(){};
     OneShotConstructor.prototype= object;
     return new OneShotConstructor();
}
clone( Array ).prototype ;  // []

39 – 一个HTML转义函数

1
2
3
4
5
6
function escapeHTML(text) {
     var replacements= { "<" : "<" , ">" : ">" , "&" : "&" , "\"" : "" "};
     return text.replace(/[<>&"]/g, function (character) {
         return replacements[character];
     });
}

40 – 避免在循环内部使用 try-catch-finally

在运行时,每次当 catch 从句被执行的时候,被捕获的异常对象会赋值给一个变量,而在 try-catch-finally 结构中,每次都会新建这个变量。

避免这样的写法:

1
2
3
4
5
6
7
8
9
var object = [ 'foo' , 'bar' ], i;
for (i = 0 , len = object.length; i <len; i++) {
     try {
         // do something that throws an exception
     }
     catch (e) {
         // handle exception
     }
}

而使用:

1
2
3
4
5
6
7
8
9
var object = [ 'foo' , 'bar' ], i;
try {
     for (i = 0 , len = object.length; i <len; i++) {
         // do something that throws an exception
     }
}
catch (e) {
     // handle exception
}

41 – 为 XMLHttpRequests 设置超时。

在一个XHR请求占用很长时间后(好比因为网络问题),你可能须要停止此次请求,那么你能够对XHR调用配套使用 setTimeout()。

1
2
3
4
5
6
7
8
9
10
11
12
13
var xhr = new XMLHttpRequest ();
xhr.onreadystatechange = function () {
     if ( this .readyState == 4 ) {
         clearTimeout(timeout);
         // do something with response data
     }
}
var timeout = setTimeout( function () {
     xhr.abort(); // call error callback
}, 60 * 1000 /* timeout after a minute */ );
xhr.open( 'GET' , url, true ); 
 
xhr.send();

此外,通常你应该彻底避免同步的Ajax请求。

42 – 处理WebSocket超时

一般,在一个WebSocket链接建立以后,若是你没有活动的话,服务器会在30秒以后断开(time out)你的链接。防火墙也会在一段时间不活动以后断开链接。

为了防止超时的问题,你可能须要间歇性地向服务器端发送空消息。要这样作的话,你能够在你的代码里添加下面的两个函数:一个用来保持链接,另外一个用来取消链接的保持。经过这个技巧,你能够控制超时的问题。

使用一个 timerID:

1
2
3
4
5
6
7
8
9
10
11
12
13
var timerID = 0 ;
function keepAlive() {
     var timeout = 15000 ;
     if (webSocket.readyState == webSocket.OPEN) {
         webSocket.send( '' );
     }
     timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
     if (timerId) {
         cancelTimeout(timerId);
     }
}

keepAlive()方法应该被添加在webSOcket链接的 onOpen() 方法的最后,而 cancelKeepAlive() 添加在 onClose() 方法的最后。

43 – 牢记,原始运算符始终比函数调用要高效。使用VanillaJS

举例来讲,不使用:

1
2
var min = Math.min(a,b);
A.push(v);

而用:

1
2
var min = a < b ? a b;
A[A.length] = v;

44 – 编码的时候不要忘记使用代码整洁工具。在上线以前使用JSLint和代码压缩工具(minification)(好比JSMin)。《省时利器:代码美化与格式化工具

45 – JavaScript是难以想象的。最好的JavaScript学习资源

46 – Javascript的String.format()

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) {
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}
调用:"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")
if (!String.format) {
  String.format = function(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function(match, number) {
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}
调用:String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');

47 – 动态加载外部JavaScript或CSS文件  

function loadjscssfile(filename, filetype){
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}
 
loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

48 – 动态加载外部JavaScript并监听文件是否加载完成

function loadScript(url, callback){
    var script = document.createElement ("script")
    script.type = "text/javascript";
    if (script.readyState){ //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" || script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else { //Others
        script.onload = function(){
            callback();
        };
    }
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

49 – 变量和函数声明被提早

先来看一段代码:

var name = "Baggins";
(function () {
    // Outputs: "Original name was undefined"
    console.log("Original name was " + name);

    var name = "Underhill";
    // Outputs: "New name is Underhill"
    console.log("New name is " + name);
})();

对javascript不了解,可能会产生2个疑问:

1.为何第一次输出的不是"Baggins"

2.即便第一次不输出"Baggins"为何没有报错?

首先解释第二个疑问:为何在未定义变量name的状况下,没有报错。

这实际上是 JavaScript 解析器搞的鬼,解析器将当前做用域内声明的全部变量和函数都会放到做用域的开始处,可是,只有变量的声明被提早到做用域的开始处了,而赋值操做被保留在原处。上述代码对于解析器来讲实际上是以下这个样子滴:

var name = "Baggins";
(function () {
    var name;  //注意:name 变量被提早了!

    // Outputs: "Original name was undefined"
    console.log("Original name was " + name);

    name = "Underhill";
    // Outputs: "New name is Underhill"
    console.log("New name is " + name);
})();

理解了这个,第一个也就好理解了。这个和做用域链有关系。在执行的时候,首先会在函数内部的执行环境中寻找name,若是没有寻找到,就会一直往上(能够理解为父级)寻找。没有找到就会报错。变量如此,函数亦然。具体可见JavaScript 中对变量和函数声明的“提早(hoist)

基于此变量的声明最好是写在变量做用域的最前端

50 – 为何是===而不是==

null==undefined这个之因此成立,是由于undefined实际上也是null。而typeof null===undefined是不成立的是因为此时比较的是他们的类型。更详细的解释能够参看undefined与null的区别

51 – 关于if(statement)判断

if(statement){ //其实是执行Boolean(statement)转型操做
    console.log(true);
}else{
    console.log(false);
}

这个等同于

 if (undefined != statement && null != statement && "" != statement && 0!=statement){
       console.log("true");
 }else{
       console.log("false");
 }

基于此,定义变量初始化值的时候,若是基本类型是string,咱们赋值空字符串,若是基本类型是number咱们赋值为0,若是是引用类型,咱们能够直接定义为null。

 52 – 关于原型和原型链

什么是原型?

原型是一个对象,其余对象能够经过它实现属性继承。

什么是原型链?

每一个对象和原型都有一个原型(注:原型也是一个对象),对象的原型指向对象的父,而父的原型又指向父的父,咱们把这种经过原型层层链接起来的关系撑为原型链。这条链的末端通常老是默认的对象原型。

一小段代码加深理解:

 

var Point = function (x, y) {
    this.x = x;
    this.y = y;
}
Point.prototype.add = function (otherPoint) {
    this.x += otherPoint.x;
    this.y += otherPoint.y;
}
var p1 = new Point(3, 4);
var p2 = new Point(8, 6);
p1.add(p2);

 

一个简图来阐释一下:

(即:p1.__proto__[Point.prototype].__proto__[Object.prototype].__proto__==null)

(这就是原型链)

深刻查看原型原型继承

 53 – new运算符

 概要:new运算符的做用是建立一个对象实例。这个对象能够是用户自定义的,也能够是带构造函数的一些系统自带的对象。

 

function Person(name,age) {
      this.name=name;
      this.age=age;      
}
Person.prototype={
      getName:function(){
           return this.name;
      },
      getage:function(){
           return this.age;
      }
}
var coco=new Person('coco',12);
console.log(coco.getName());

 

new操做符会让构造函数产生以下变化:

1.建立一个新的对象;

2.将构造函数的做用域赋值给新对象(所以this对象就指向了这个新的对象)

3.执行构造函数中的代码(为这个新对象添加属性);

4.返回新对象

要理解这4点请看上面例子对应的等同变体:

function Person(name,age) {
      this.name=name;
      this.age=age;      
}
Person.prototype={
      getName:function(){
           return this.name;
      },
      getage:function(){
           return this.age;
      }
}
var coco={};
coco.__proto__=Person.prototype
Person.call(coco,'coco',12);

54 – call/apply改变函数中this的指向

// 定义一个全局函数
function foo() {
    if (this === window) {
        console.log("this is window.");
    }
}

// 函数foo也是对象,因此能够定义foo的属性boo为一个函数
foo.boo = function () {
    if (this === foo) {
        console.log("this is foo.");
    } else if (this === window) {
        console.log("this is window.");
    }
};
// 等价于window.foo();
foo();  // this is window.

// 能够看到函数中this的指向调用函数的对象
foo.boo();  // this is foo.

// 使用apply改变函数中this的指向
foo.boo.apply(window);  // this is window.

55 – input的type类型的修改问题

要实现一个相似登录框提示用户输入的功能,咱们会想到placeholder,可是咱们知道placeholder是html5的新属性,因此在不一样的浏览器下的兼容性是有问题的。因而想到直接修改文本框的类型,当尝试使用jQuery来修改元素的属性的时候,很不幸,在chrome的控制台下会直接输出error信息:"Uncaught type property can't be changed"当尝试使用原生的javascript来修改:input.setAttribute("type","password");在ie8及下版本是彻底不支持的。由于这个时候type是只读的。另外提供一个实现placeholder功能的比较好的js插件,见这里

56 – 关于外挂文件和将脚本写在$(document).ready()中的误区

咱们经常被告知,js要和html文档分离,而且内置的脚本最好要写在$(document).ready()而不是$(window).load()中。但事实上,这个并非万能法则。咱们外挂的js文档要加载,须要一次服务器请求,虽然如今的浏览器支持的请求数成倍增长,然而若是成千上万的人一块儿访问网站,请求给服务器形成的压力也是可想而知的,请求的时间若是再算在内的话,将脚本直接包含在网页底部或许能节省一些时间。另外若是页面文档很是大,加载起来很是慢(特别是有大量外链的时候),这个时候你若是将控件的事放在$(document).ready()中,就极可能当你想触发按钮的事件的时候,文档还没有加载完成。所以这个时候建议将这部分js脚本放在对应文档的底部(直接放在文档后面也多是有问题的,若是事件代码包含还没有加载好的文档节点就会有错)。

 

 

总结

我知道还有不少其余的技巧,窍门和最佳实践,因此若是你有其余想要添加或者对我分享的这些有反馈或者纠正,请在评论中指出。

本文大部分在自:伯乐在线 和我的总结

相关文章
相关标签/搜索