欢迎来到福编程网,本站提供各种互联网专业知识!

使用Javascript和DOM Interfaces来处理HTML

发布时间:2006-10-09 作者: 来源:转载
1、创建表格Samplecode-TraversinganHTMLTablewithJavaScriptandDOMInterfaces[Ctrl+A全选注:如需引入外部Js需刷新才能执行]Notetheorderinwhichwecreatedtheelementsandthetextnode:FirstwecreatedtheTABLEelement.Next,wecreatedtheTBO
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:

...

cellisrow0column0cellisrow0column1
cellisrow1column0cellisrow1column1

...

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.

Samplecode-TraversinganHTMLTablewithJavaScriptandDOMInterfaces




[编辑]

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.





取自"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

相关推荐