更优美的javaScript(2)

1,事件委托:

事件是JavaScript非常重要的一部分。我们想给一个列表中的链接绑定点击事件,一般的做法是写一个循环,给每个链接对象绑定事件,HTML代码如下:

<h2>Great Web resources</h2>

<ul id="resources">

  <li><a href="http://opera.com/wsc">Opera Web Standards Curriculum</a></li>

  <li><a href="http://sitepoint.com">Sitepoint</a></li>

  <li><a href="http://alistapart.com">A List Apart</a></li>

  <li><a href="http://yuiblog.com">YUI Blog</a></li>

  <li><a href="http://blameitonthevoices.com">Blame it on the voices</a></li>

  <li><a href="http://oddlyspecific.com">Oddly specific</a></li>

</ul>

脚本如下:

// Classic event handling example

(function(){

  var resources = document.getElementById('resources');

  var links = resources.getElementsByTagName('a');

  var all = links.length;

  for(var i=0;i<all;i++){

    // Attach a listener to each link

    links[i].addEventListener('click',handler,false);

  };

  function handler(e){

    var x = e.target; // Get the link that was clicked

    alert(x);

    e.preventDefault();

  };

})();

更合理的写法是只给列表的父对象绑定事件,代码如下:

(function(){

  var resources = document.getElementById('resources');

  resources.addEventListener('click',handler,false);

  function handler(e){

    var x = e.target; // get the link tha

    if(x.nodeName.toLowerCase() === 'a'){

      alert('Event delegation:' + x);

      e.preventDefault();

    }

  };

})();

 

2,单体模式的写法:

var myApplication = function(){

  var name = 'Chris';

  var age = '34';

  var status = 'single';

  function createMember(){

    // [...]

  }

  function getMemberDetails(){

    // [...]

  }

  return{

    create:createMember,

    get:getMemberDetails

  }

}();

//myApplication()get() and myApplication().create() now work.

 

 

3,对象传参:

function doSomething() {

  // Leaves the function if nothing is passed

  if (!arguments[0]) {

  return false;

  }

  var oArgs   = arguments[0]

  arg0    = oArgs.arg0 || "",

  arg1    = oArgs.arg1 || "",

  arg2    = oArgs.arg2 || 0,

  arg3    = oArgs.arg3 || [],

arg4    = oArgs.arg4 || false;

//do something use the arguments

}

//call function like this

doSomething({

arg0:donald duck

  arg1    : "helloKitty",

  arg2    : 17,

  arg4    : true

});

 

4,变量转换:

var myVar   = "3.14159",

str     = ""+ myVar,//  to string

int     = ~~myVar,  //  to integer

float   = 1*myVar,  //  to float

bool    = !!myVar,  /*  to boolean - any string with length

and any number except 0 is true */

array   = [myVar];  //  to array

 

5,使用document.createDocumentFragment()动态地追加多个元素到文档中

function createList() {

  var aLI = ["first item", "second item", "third item",

  "fourth item", "fith item"];

  // Creates the fragment

  var oFrag   = document.createDocumentFragment();

  while (aLI.length) {

    var oLI = document.createElement("li");

    // Removes the first item from array and appends it

    // as a text node to LI element

    oLI.appendChild(document.createTextNode(aLI.shift()));

    oFrag.appendChild(oLI);

  }

  document.getElementById('myUL').appendChild(oFrag);

}

 

6,循环中使用标签退出

outerloop:

for (var iI=0;iI<5;iI++) {

  if (somethingIsTrue()) {

  // Breaks the outer loop iteration

  break outerloop;

  }

  innerloop:

  for (var iA=0;iA<5;iA++) {

    if (somethingElseIsTrue()) {

    // Breaks the inner loop iteration

    break innerloop;

  }

  }

}

 

7,JSON的方法:

// 这是JSON字符串,比如从AJAX获取字符串信息
var my_json_string = '{ "prop": "val" }';
 
// 将字符串反序列化成对象
var my_obj = JSON.parse( my_json_string );
 
alert( my_obj.prop == 'val' ); //  提示 true, 和想象的一样!
 
// 将对象序列化成JSON字符串
var my_other_json_string = JSON.stringify( my_obj );

 

原文地址:https://www.cnblogs.com/happyPawpaw/p/2480627.html