30. Table sorting and DOM mapping

1.

  var oul = document.getElemntById("ul")

  var olis = oul.getElementByTagName("li")

  1) First convert the element collection class array into an array

  var ary = [] .slice.call (olis)

  2) Sort the array: sort according to the size of the content in each li

  ary.sort(function(a,b) {

    return parseFloat(a.innerHTML) - parseFloat( b.innerHTML)

  })

  3) According to the latest order stored in ary, add the corresponding li to the page in turn

 var frg = document.createDocumentFragment()

  for (var i = 0;i<ary.length;i++) {

    frg.appendChild(ary[i])

  }

  oul.appendChild(frg);

  frg = null;

2. DOM mapping mechanism

  Meaning: The tags in the page and the element objects (element collections) obtained by js are tightly bound together. If the html structure in the page changes, it does not need to be re-fetched in js, and the content in the collection will follow automatically. Change

  var oul = document.getElementById("oul")

  var olis = oul.getElementByTagName("li")

  console.log(olis.length); // 5

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

  oul.appendChild(oli);

  console.log(olis.length); // 6 is not re-acquired, but the length and content of the oli collection will automatically change accordingly

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325015757&siteId=291194637