dom2
1. *創建和刪除節點
1. 創建節點:
創建元素節點:3步:
1. 創建空元素對象:
var newElem=document.createElement("標簽名");
比如:var a=document.createElement("a");
<a></a>
2. 設置必要屬性:
newElem.屬性名="值";
newElem.innerHTML="文本";
比如:a.href="http://tmooc.cn";
a.innerHTML="go to tmooc";
<a href="http://tmooc.cn">go to tmooc</a>
3. 將元素對象掛載到指定父元素下:2種:
追加:parent.appendChild(newElem);
強調:只有向已經在頁面中的父元素追加新節點,才導致渲染
比如: div.appendChild(a);
<div>
...
<a href="http://tmooc.cn">go to tmooc</a>
</div>
2. 創建文檔片段:documentfragment
文檔片段:內存中,臨時存儲多個子節點的存儲空間
何時使用文檔片段?反復追加多個平級元素
解決:先將所有平級元素先追加到文檔片段中
將文檔片段一次性追加到父元素下
*文檔片段不參與追加*
1. *創建、刪除:
插入新元素:parent.insertBefore(newElem,oldElem);
刪除節點:parent.removeChild(oldElem);
oldElem.parentNode.removeChild(oldElem);
替換節點:parent.replaceChild(newElem,oldElem);
課堂練習:級聯下拉列表:
1. onchange:當內容發生改變時觸發
2. select對象:selectedIndex屬性:當前選中項的下標
2. *常用HTML DOM對象:Table Select Form
Table對象:
屬性:
tHead tFoot tBodies
rows: 獲得表中所有行對象
rows[i]: 獲得表中小標為i的一個行對象
方法:
var newRow=insertRow(rowIndex):
rowIndex寫-1,表示在末尾追加
比如:insertRow(-1)
核心DOM:var newRow=document.createElement("tr") table.appendChild(newRow)
deleteRow(rowIndex):
比如:currRow.parentNode.removeChild(currRow);
table.deleteRow(currRow.rowIndex)
TableRow對象:代表table對象中的某一個tr對象
table.rows集合,就是一組TableRow對象的集合
屬性:
cells: 當前行中所有td對象
cells[i]: 獲得當前行中下標為i的td
rowIndex: 當前行的下標位置,專用于刪除行
方法:
var newCell=insertCell(index)
比如:insertCell(3)
核心DOM:var td=document.createElement("td");
tr.appendChild(td);
deleteCell(index)
TableCell對象:
屬性:cellIndex
Select對象:
屬性:
options: 獲得當前select下所有option
options[i]: 獲得當前select下i位置的option
selectedIndex: 獲得當前選中的option的下標
方法:
add(新option對象)
比如: select.appendChild(newOpt);
select.add(newOpt);
remove(index)
Option對象:指代select下某一個option元素
如何創建:var newOpt=new Option(innerHTML,value)
創建option對象同時,設置對象的innerHTML和value屬性
相當于:var newOpt=document.createElement("option");
newOpt.innerHTML="內容"
newOpt.value="值";
一句話:創建,設置,追加
select.add(new Option(innerHTML,value));
屬性:index: 獲取當前option的下標位置,專用于刪除
selected: 可當做bool用
如果當前option被選中,返回true
否則,返回false
Form對象:
如何找到一個form對象
var form=document.forms[i/name];
如何找到form中的一個數據采集元素:
var elem=form.elements[i/name]
事件:onsubmit:在正式提交表單前自動觸發
?
轉載于:https://www.cnblogs.com/handsomeboyyyyyy/p/6854082.html
總結
- 上一篇: Linux文件大小排序
- 下一篇: [LeetCode] 303. Rang