你可能不知道的10个JavaScript小技巧

发表于:2010-8-16 10:51

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:梦想天空( 博客园)    来源:51Testing软件测试网采编

  8.使用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); 
}

  9.为replace()方法传递一个函数

  有的时候你想替换字符串的某个部分为其它的值,最好的方法就是给String.replace()传递一个独立的函数。下面是一个简单例子:

var sFlop   = "Flop: [Ah] [Ks] [7c]"; 
var aValues = {"A":"Ace","K":"King",7:"Seven"}; 
var aSuits  = {"h":"Hearts","s":"Spades", 
"d":"Diamonds","c":"Clubs"}; 
sFlop   = sFlop.replace(/\[\w+\]/gi, function(match) { 
  match   = match.replace(match[2], aSuits[match[2]]); 
  match   = match.replace(match[1], aValues[match[1]] +" of "); 
  return match; 
}); 
// string sFlop now contains: 
// "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"

  10.循环中标签的使用

  有的时候,循环中又嵌套了循环,你可能想在循环中退出,则可以用标签:

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; 
  } 
  } 
}

33/3<123
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号