Data binding method:
1. Use the method of dynamically creating element nodes and appending them to the page to implement data binding (add the dynamically added li Add to ul)
var oUl = document.getElementById('ul')for(var i = 0;i<ary.length;i++){var cur = ary[i];var oLi = document.createElement('li'); oLi.innerHTML = "<span>"+(i+1)+"</span>"+cur.title oUl.appendChild(oLi) }
Advantages: Append the content that needs to be dynamically bound to the page one by one, and modify the original Elements have no impact
Disadvantages: Whenever we create a li, we add it to the page, triggering a DOM reflow. Finally, too many reflows are triggered, which affects our performance.
2. String splicing method: first loop the data that needs to be bound, and then splice the labels that need to be dynamically bound together in the form of strings. (String splicing is the most commonly used way to bind data in our future work)
str = ""( i = 0;i<ary.length;i++ cur =+="<li>"+="<span>"+(i+1)+"</span>"+=+="</li>"+= str;//oUl.innerHTML(把之前的li以字符串的方式获取到)+str;拼接完成的整体还是字符串 最后再把字符串统一的添加到页面中,浏览器还需要把字符串渲染成为对应的标签
Disadvantages: We add the newly spliced string to In ul, The original li-bound events have disappeared
Advantages: Splice the content in advance, and finally add it to In the page, only one reflow is triggered
In-depth knowledge of DOM in JS: Reflow should be minimized
Reflow (reflow): When the HTML structure in the page changes (elements are added, deleted, and the position changes), the browser needs to recalculate the latest DOM structure and re-render the current page.
Redraw: Part of the style of a certain element has changed (background color), the browser only needs to re-render the current Elements
3. Document fragments:
var frg = document.createDocumentFragment();
for(var i = 0;i<ary.length;i++){var cur = ary[i];var oLi = document.createElement('li'); oLi.innerHTML = "<span>"+(i+1)+"</span>"+cur.title frg.appendChild(oLi) } oUl.appendChild(frg); frg = null;
The above is the detailed content of Detailed explanation of data binding and DOM reflow examples. For more information, please follow other related articles on the PHP Chinese website!