使用Javascript和DOM Interfaces来处理HTML

1、创建表格

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]
Notetheorderinwhichwecreatedtheelementsandthetextnode:

FirstwecreatedtheTABLEelement.
Next,wecreatedtheTBODYelement,whichisachildoftheTABLEelement.
Next,weusedalooptocreatetheTRelements,whicharechildrenoftheTBODYelement.
ForeachTRelement,weusedalooptocreatetheTDelements,whicharechildrenofTRelements.
ForeachTDelement,wethencreatedthetextnodewiththetablecell'stext.
OncewehavecreatedtheTABLE,TBODY,TR,andTDelementsandthenthetextnode,wethenappendeachobjecttoitsparentintheoppositeorder:



First,weattacheachtextnodetoitsparentTDelementusing
mycurrent_cell.appendChild(currenttext);
Next,weattacheachTDelementtoitsparentTRelementusing
mycurrent_row.appendChild(mycurrent_cell);
Next,weattacheachTRelementtotheparentTBODYelementusing
mytablebody.appendChild(mycurrent_row);
Next,weattachtheTBODYelementtoitsparentTABLEelementusing
mytable.appendChild(mytablebody);
Next,weattachtheTABLEelementtoitsparentBODYelementusing
mybody.appendChild(mytable);


Rememberthistechnique.YouwilluseitfrequentlyinprogrammingfortheW3CDOM.First,youcreateelementsfromthetopdown;thenyouattachthechildrentotheparentsfromthebottomup.

Here'stheHTMLmarkupgeneratedbytheJavaScriptcode:

...
<TABLEborder=5>
<tr><td>cellisrow0column0</td><td>cellisrow0column1</td></tr>
<tr><td>cellisrow1column0</td><td>cellisrow1column1</td></tr>
</TABLE>
...

Here'stheDOMobjecttreegeneratedbythecodefortheTABLEelementanditschildelements:

Image:sample1-tabledom.jpg

YoucanbuildthistableanditsinternalchildelementsbyusingjustafewDOMmethods.Remembertokeepinmindthetreemodelforthestructuresyouareplanningtocreate;thiswillmakeiteasiertowritethenecessarycode.IntheTABLEtreeofFigure1theelementTABLEhasonechild,theelementTBODY.TBODYhastwochildren.EachTBODY'schild(TR)hasonechild(TD).Finally,eachTDhasonechild,atextnode.


2、

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]
Inthisexample,wesetthemyPvariabletotheDOMobjectforthesecondpelementinsidethebody:



First,wegetalistofallthebodyelementsvia
document.getElementsByTagName("body")
SincethereisonlyonebodyelementinanyvalidHTMLdocument,thislistwillhaveonlyoneitem.
Next,wegetthefirstelementonthatlist,whichwillbetheobjectforthebodyelementitself,via
myBody=myDocumentElements.item(0);
Next,wegetallthepelementsthatarechildrenofthebodyvia
myBodyElements=myBody.getElementsByTagName("p");
Finally,wegettheseconditemfromthelistofpelementsvia
myP=myBodyElements.item(1);


Image:sample2a2.jpg

OnceyouhavegottentheDOMobjectforanHTMLelement,youcansetitsproperties.Forexample,ifyouwanttosetthestylebackgroundcolorproperty,youjustadd:

myP.style.background="rgb(255,0,0)";
//settinginlineSTYLEattribute


[编辑]

CreatingTextNodeswithdocument.createTextNode(..)
UsethedocumentobjecttoinvokethecreateTextNodemethodandcreateyourtextnode.Youjustneedtopassthetextcontent.Thereturnvalueisanobjectthatrepresentsthetextnode.

myTextNode=document.createTextNode("world");

ThismeansthatyouhavecreatedanodeofthetypeTEXT_NODE(apieceoftext)whosetextdatais"world",andmyTextNodeisyourreferencetothisnodeobject.ToinsertthistextintoyourHTMLpage,youneedtomakethistextnodeachildofsomeothernodeelement.



[编辑]

InsertingElementswithappendChild(..)
So,bycallingmyP.appendChild([node_element]),youaremakingtheelementanewchildofthesecondPelement.

myP.appendChild(myTextNode);

Aftertestingthissample,notethatthewordshelloandworldaretogether:helloworld.Sovisually,whenyouseetheHTMLpageitseemslikethetwotextnodeshelloandworldareasinglenode,butrememberthatinthedocumentmodel,therearetwonodes.ThesecondnodeisanewnodeoftypeTEXT_NODE,anditisthesecondchildofthesecondPtag.ThefollowingfigureshowstherecentlycreatedTextNodeobjectinsidethedocumenttree.

Image:sample2b2.jpg

createTextNodeandappendChildisasimplewaytoincludewhitespacebetweenthewordshelloandworld.AnotherimportantnoteisthattheappendChildmethodwillappendthechildafterthelastchild,justlikethewordworldhasbeenaddedafterthewordhello.SoifyouwanttoappendaTextNodebetweenhelloandworldyouwillneedtouseinsertBeforeinsteadofappendChild.


[编辑]

CreatingNewElementswiththedocumentobjectandthecreateElement(..)method
YoucancreatenewHTMLelementsoranyotherelementyouwantwithcreateElement.Forexample,ifyouwanttocreateanewPelementasachildoftheBODYelement,youcanusethemyBodyinthepreviousexampleandappendanewelementnode.Tocreateanodesimplycalldocument.createElement("tagname").Forexample:

myNewPTAGnode=document.createElement("p");
myBody.appendChild(myNewPTAGnode);

Image:sample2c.jpg



[编辑]

RemovingnodeswiththeremoveChild(..)method
Eachnodecanberemoved.ThefollowinglineremovesthetextnodewhichcontainsthewordworldofthemyP(secondPelement).

myP.removeChild(myTextNode);

FinallyyoucanaddmyTextNode(whichcontainsthewordworld)intotherecentlycreatedPelement:

myNewPTAGnode.appendChild(myTextNode);

Thefinalstateforthemodifiedobjecttreelookslikethis:

Image:sample2d.jpg



[编辑]

Creatingatabledynamically(backtoSample1.html)
Fortherestofthisarticlewewillcontinueworkingwithsample1.html.Thefollowingfigureshowsthetableobjecttreestructureforthetablecreatedinthesample.



[编辑]

ReviewingtheHTMLTablestructure
Image:sample1-tabledom.jpg



[编辑]

Creatingelementnodesandinsertingthemintothedocumenttree
Thebasicstepstocreatethetableinsample1.htmlare:

Getthebodyobject(firstitemofthedocumentobject).
Createalltheelements.
Finally,appendeachchildaccordingtothetablestructure(asintheabovefigure).Thefollowingsourcecodeisacommentedversionforthesample1.html.
Attheendofthestartfunctionthereisanewlineofcode.Thetable'sborderpropertywassetusinganotherDOMmethod,setAttribute.setAttributehastwoarguments:theattributenameandtheattributevalue.YoucansetanyattributeofanyelementusingthesetAttributemethod.
<head>
<title>Samplecode-TraversinganHTMLTablewithJavaScriptandDOMInterfaces</title>
<script>
functionstart(){
//getthereferenceforthebody
varmybody=document.getElementsByTagName("body").item(0);
//createsanelementwhosetagnameisTABLE
mytable=document.createElement("TABLE");
//createsanelementwhosetagnameisTBODY
mytablebody=document.createElement("TBODY");
//creatingallcells
for(j=0;j<2;j++){
//createsanelementwhosetagnameisTR
mycurrent_row=document.createElement("TR");
for(i=0;i<2;i++){
//createsanelementwhosetagnameisTD
mycurrent_cell=document.createElement("TD");
//createsaTextNode
currenttext=document.createTextNode("cellisrow"+j+",column"+i);
//appendstheTextNodewecreatedintothecellTD
mycurrent_cell.appendChild(currenttext);
//appendsthecellTDintotherowTR
mycurrent_row.appendChild(mycurrent_cell);
}
//appendstherowTRintoTBODY
mytablebody.appendChild(mycurrent_row);
}
//appendsTBODYintoTABLE
mytable.appendChild(mytablebody);
//appendsTABLEintoBODY
mybody.appendChild(mytable);
//setstheborderattributeofmytableto2;
mytable.setAttribute("border","2");
}
</script>
</head>
<bodyonload="start()">
</body>
</html>



[编辑]

ManipulatingthetablewithDOMandCSS


[编辑]

Gettingatextnodefromthetable
ThisexampleintroducestwonewDOMattributes.FirstitusesthechildNodesattributetogetthelistofchildnodesofmycel.ThechildNodeslistincludesallchildnodes,regardlessofwhattheirnameortypeis.LikegetElementsByTagName,itreturnsalistofnodes.ThedifferenceisthatgetElementsByTagNameonlyreturnselementsofthespecifiedtagname.Onceyouhavethereturnedlist,useitem(x)methodtoretrievethedesiredchilditem.Thisexamplestoresinmyceltextthetextnodeofthesecondcellinthesecondrowofthetable.Then,todisplaytheresultsinthisexample,itcreatesanewtextnodewhosecontentisthedataofmyceltextandappendsitasachildoftheBODYelement.

Ifyourobjectisatextnode,youcanusethedataattributeandretrievethetextcontentofthenode.
mybody=document.getElementsByTagName("body").item(0);
mytable=mybody.getElementsByTagName("table").item(0);
mytablebody=mytable.getElementsByTagName("tbody").item(0);
myrow=mytablebody.getElementsByTagName("tr").item(1);
mycel=myrow.getElementsByTagName("td").item(1);
//firstitemelementofthechildNodeslistofmycel
myceltext=mycel.childNodes.item(0);
//contentofcurrenttextisthedatacontentofmyceltext
currenttext=document.createTextNode(myceltext.data);
mybody.appendChild(currenttext);



[编辑]

Gettinganattributevalue
Attheendofsample1thereisacalltosetAttributeonthemytableobject.Thiscallwasusedtosettheborderpropertyofthetable.Toretrievethevalueoftheattribute,usethegetAttributemethod:

mytable.getAttribute("border");



[编辑]

Hidingacolumnbychangingstyleproperties
OnceyouhavetheobjectinyourJavaScriptvariable,youcansetstylepropertiesdirectly.Thefollowingcodeisamodifiedversionofsample1.htmlinwhicheachcellofthesecondcolumnishiddenandeachcellofthefirstcolumnischangedtohavearedbackground.Notethatthestylepropertywassetdirectly.

<html>
<bodyonload="start()">
</body>
<script>
functionstart(){
varmybody=document.getElementsByTagName("body").item(0);
mytable=document.createElement("TABLE");
mytablebody=document.createElement("TBODY");
for(j=0;j<2;j++){
mycurrent_row=document.createElement("TR");
for(i=0;i<2;i++){
mycurrent_cell=document.createElement("TD");
currenttext=document.createTextNode("cellis:"+i+j);
mycurrent_cell.appendChild(currenttext);
mycurrent_row.appendChild(mycurrent_cell);
//setthecellbackgroundcolor
//ifthecolumnis0.Ifthecolumnis1hidethecel
if(i==0){
mycurrent_cell.style.background="rgb(255,0,0)";
}else{
mycurrent_cell.style.display="none";
}
}
mytablebody.appendChild(mycurrent_row);
}
mytable.appendChild(mytablebody);
mybody.appendChild(mytable);
}
</script>
</html>

取自"http://developer.mozilla.org/cn/docs/%E4%BD%BF%E7%94%A8Javascript%E5%92%8CDOM_Interfaces%E6%9D%A5%E5%A4%84%E7%90%86HTML"

页面分类: DOM

相关推荐

评论

展开