JS 문서 조각에 요소를 추가하는 방법에 대한 자세한 설명(그래픽 튜토리얼)

亚连
풀어 주다: 2018-05-18 14:36:24
원래의
1132명이 탐색했습니다.

JS를 통해 DOM 노드의 작업은 노드 단위로 수행될 수 있습니다. 예를 들어 노드를 추가하려면 createElement, createTextNode를 사용하고 appendChild를 사용하여 바인딩할 수 있습니다. 그런 다음 appendChild 또는 insertBefor를 사용하여 DOM 트리에 추가합니다. 그러나 DOM 트리에 많은 수의 노드를 동적으로 추가하려면 매우 번거로운 작업이 됩니다. 예:

var arrText = ["one","two","three","four","five","six","seven","eight","nine","ten"];
for(var i = 0;i<arrText.length;i++){
    var oP = document.createElement("p");
    var oText = document.createTextNode(arrText[i]);
    oP.appendChild(oText);
    document.body.appendChild(oP);
}
로그인 후 복사
이 코드는 document.body.appendChild()를 10번 호출하므로 매번 페이지가 새로 고쳐지므로

"을 사용할 수 있습니다. DocumentFragments":

var arrText = ["one","two","three","four","five","six","seven","eight","nine","ten"];
var oFragment = document.createDocumentFragment();
for(var i = 0;i<arrText.length;i++){
    var oP = document.createElement("p");
    var oText = document.createTextNode(arrText[i]);
    oP.appendChild(oText);
    oFragment.appendChild(oP);
}
document.body.appendChild(oFragment);
로그인 후 복사
function appendError (id, str) {  
        var spanNew = document.createElement("span" ); // 创建span 
        spanNew.id = id + "span" ; // 生成spanid 
        spanNew.style.color = "red" ;  
        spanNew.appendChild(document.createTextNode(str));// 给span添加内容 
        var inputId = document.getElementById(id);  
        inputId.parentNode.insertBefore(spanNew, inputId.nextSibling);// 给需要添加元素后面添加span 
//如果需要在前面添加改成就可以了 
inputId.parentNode.insertBefore(spanNew, inputId);// 给需要添加元素后面添加span 
    }
로그인 후 복사

<script type="text/javascript"><!--
function $(nodeId) 
{ 
return document.getElementById(nodeId); 
} 
function $Name(tagName) 
{ 
return document.getElementsByTagName(tagName); 
}
function replaceMsg() 
{ 
var newNode = document.createElement("P");//创建一个P标签 
newNode.innerHTML = "<font color=&#39;red&#39;>替换后的文字</font>"; 
var oldNode = $Name("P")[0];//获取body里面第一个p元素 
oldNode.parentNode.replaceChild(newNode,oldNode);//直接替换了标签 
}
function removeMsg() 
{ 
var node = $("p2");//p标签 
var nodeBtn = $("remove");//按钮 
//node.parentNode.removeChild(node); //下面效果相同 
document.body.removeChild(node);//在body中删除id为P2的元素 
//nodeBtn.parentNode.removeChild(nodeBtn);//删除该按钮 
document.body.removeChild(nodeBtn); 
//document.body.removeNode();执行这条语句将清空body里面的任何元素 
}
function addbefore() 
{ 
var newNode = document.createElement("p");//创建P标签 
//var newText = document.createTextNode("前面添加的元素"); 
//newNode.appendChild(newText);//与下面效果一样 
newNode.innerHTML = "<font color=&#39;red&#39;>前面添加的元素</font>";//书写P标签里面的内容 
var oldNode = $("p3");//目标标签 
//document.body.insertBefore(newNode,oldNode); 
oldNode.parentNode.insertBefore(newNode,oldNode);//在目标标签前面 添加元素 
}
function addlast() 
{ 
var newNode = document.createElement("p");//创建P标签 
//var newText = document.createTextNode("后面添加的元素"); 
//newNode.appendChild(newText);//与下面效果一样 
newNode.innerHTML = "<font color=&#39;red&#39;>后面添加的元素</font>"; 
var oldNode = $("p3");
oldNode.appendChild(newNode); 
//document.body.appendChild(newNode);//如果使用该方法,则在body的最后添加元素 
}
window.onload = function addArrayMsg() 
{ 
var arrayMsg = [&#39;one&#39;,&#39;two&#39;,&#39;three&#39;,&#39;four&#39;,&#39;five&#39;];//创建数组 
var fragment = document.createDocumentFragment();//创建文档片段 
var newNode ; 
for (var i=0 ;i<arrayMsg.length ;i++ ) 
{ 
newNode = document.createElement("P");//创建P标签 
var nodeText = document.createTextNode(arrayMsg[i]);//创建文本标签,value为数组里面的值 
newNode.appendChild(nodeText);// 
fragment.appendChild(newNode);//把P标签追加到fragment里面 
} 
document.body.appendChild(fragment);//把fragment追加到body里面 
}
function addRow() 
{ 
var tab = $("myTable"); 
//tab.createCaption().innerHTML="<font color=&#39;red&#39;>我的表格</font>"; 
var oldTr = $("handleTr"); 
var newTr = tab.insertRow();//创建一行 
var newTd1 = newTr.insertCell();//创建一个单元格 
var newTd2 = newTr.insertCell();//创建一个单元格 
newTd1.innerHTML = "<input type=&#39;checkbox&#39; />"; 
newTd2.innerHTML = "<input type=&#39;text&#39; />";
}
function removeRow() 
{ 
var tab = $("myTable"); 
// if(tab.rows.length>0){ 
// tab.deleteRow(); 
// if(tab.rows.length==1) 
// tab.deleteCaption(); 
// }
var cbbox ; 
for(var i=0;i<tab.rows.length;i++){ 
cbbox = tab.rows[i].childNodes[0].childNodes[0];//获取input元素 
if(cbbox.checked){
tab.deleteRow(i--); 
} 
} 
}
//全选 
function selAll(value){ 
var items = document.all.tags("input");//获取页面上所有的input元素 
for(var i = 0;i<items.length;i++){ 
if(items[i].type=="checkbox"){//判断类型是否为checkbox 
items[i].checked = value.checked; 
} 
} 
}
function getInputValue() 
{ 
var inputArray = new Array();//创建一个数组 
var tab = $("myTable"); 
var tbInput; 
for(var i=0;i<tab.rows.length;i++){ 
tbInput = tab.rows[i].childNodes[1].childNodes[0].value; 
if(tbInput!=""&&tbInput!=null) 
inputArray.push(tbInput); 
} 
inputArray = inputArray.join("*^&");//默认以","号连接 
$("showValue").value = inputArray; 
} 
var x =&#39;10+20&#39;; 
("alert(x);") 
// --></script> 
</head> 
<body> 
<p id="p1">Hello World! 
<input type="button" value="替换内容" onclick="replaceMsg();" /> 
<p id="p2">我可以被删除! 
<input type="button" id="remove" value="删除它" onclick="removeMsg();" /> 
<p id="p3">在我上下添加一个元素吧! 
<input type="button" id="addbefore" value="前面添加" onclick="addbefore();" /> 
<input type="button" id="addlast" value="后面添加" onclick="addlast();" /> 
<div style="border:1px solid blue;height:300px"> 
<table id="myTable" cellpadding="0" cellspacing="0" border="1px solid blue" style="padding:4px;" style="padding:4px;"> 
</table> 
<input type="checkbox" onclick="selAll(this);" /> 
<input type="button" value="添加一行" id="addRow" onclick="addRow();" /> 
<input type="button" value="删除一行" id="removeRow" onclick="removeRow();" />
<textarea rows="5" cols="25" id="showValue" />
로그인 후 복사
    위 내용은 제가 모두를 위해 편집한 내용입니다. 앞으로 모든 분들에게 도움이 되기를 바랍니다.
  1. 관련 기사:

js

소수점 두 자리 유지 방법


js

및 CSS 파일 로드 및 제거 단계 자세한 설명

p5.
js

불꽃놀이 달성 효과

위 내용은 JS 문서 조각에 요소를 추가하는 방법에 대한 자세한 설명(그래픽 튜토리얼)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!