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