JS jQuery 의 append 기능 실현

2197 단어 jsappendjQuery
Show Me The Code

HTMLElement.prototype.appendHTML = function(html) {
	let divTemp = document.createElement("div");
	let nodes = null;
	let fragment = document.createDocumentFragment();
	divTemp.innerHTML = html;
	nodes = divTemp.childNodes;
	nodes.forEach(item => {
		fragment.appendChild(item.cloneNode(true));
	})
	//       append
	this.appendChild(fragment);
	//       prepend
	// this.insertBefore(fragment, this.firstChild);
	nodes = null;
	fragment = null;
};
효과 테스트
html

<style>
.child {
  height: 50px;
  width: 50px;
  background: #66CCFF;
  margin-bottom: 1em;
}
</style>

<div id="app">
  <div class="child">
  <div class="child">
</div>
js

let app = document.getElementById('app');
let child = `<div class="child">down</div>`;
app.appendHTML(child);
효과.

PS
또한,현재 위 에 삽입 하려 면 코드 에 있 는 this.append Child(fragment)만 필요 합 니 다.this.insertBefore(fragment,this.firstChild)로 변경 하기;
다른 방법

var div2 = document.querySelector("#div2");
  div2.insertAdjacentHTML("beforebegin","<p>hello world</p>");//               
  div2.insertAdjacentHTML("afterbegin","<p>hello world</p>");//                         
  div2.insertAdjacentHTML("beforeend","<p>hello world</p>");//                           
  div2.insertAdjacentHTML("afterend","<p>hello world</p>");//                
브 라 우 저의 렌 더 링 효과:

이 방법 은 i 의 최초 방법 이기 때문에 호환성 이 매우 좋다.
이상 은 JS 가 jQuery 의 append 기능 을 실현 하 는 상세 한 내용 입 니 다.JS 가 jQuery append 를 실현 하 는 것 에 관 한 자 료 는 저희 의 다른 관련 글 을 주목 해 주 십시오!

좋은 웹페이지 즐겨찾기