Học JavaScript qua ví dụ part 72 doc

9 204 0
Học JavaScript qua ví dụ part 72 doc

Đang tải... (xem toàn văn)

Thông tin tài liệu

ptg 636 Chapter 15 • The W3C DOM and JavaScript 15.7.4 Inserting Before a Node The insertBefore() method allows you to insert a child node before the specified node, called the reference node, and if the reference node is null, this will insert the node at the end of a list of child nodes. Example 15.8 demonstrates how to insert a new paragraph node into a DOM before another node. FORMAT insertBefore(newElement, targetElement) EXAMPLE document.body.insertBefore(newPara, firstPara); EXAMPLE 15.8 <html> <head><title>Inserting Before</title> <style type="text/css"> p { font-style:arial; color:darkblue; font-size:18; } </style> <script type="text/javascript"> 1 function insertMessage() { 2 var newPara = document.createElement("p"); 3 var newText = document.createTextNode("I am inserting myself above you!"); // If you copy this, don’t break the lines. 4 newPara.appendChild(newText); 5 var firstPara = document.getElementById("firstp"); 6 document.body.insertBefore(newPara, firstPara); } </script> </head> 7 <body onload="insertMessage()"> <p id=”firstp”>I was supposed to be first.</p> </body> </html> EXPLANATION 1 Once the page has loaded, this function will be called. 2 With the createElement() method, a new paragraph is created. A reference to it is assigned to a variable, newPara. From the Library of WoweBook.Com ptg 15.7 Modifying the DOM (Appending, Copying, and Removing Nodes) 637 15.7.5 Creating Attributes for Nodes The setAttribute() method creates a new attribute for an element. If an attribute with that name (nodeName) already exists in the element, it is replaced by the new one. See the section “Cloning Nodes” later in this chapter for more examples. 3 Now we are going to insert some text into the paragraph with the createTextNode() method. 4 After creating a reference to the new text, it is appended to the paragraph with the appendChild() method. 5 The document.getElementById() returns a reference to the first paragraph. This will be the reference node, or the node in which the second paragraph will be in- serted. 6 The new paragraph is inserted above the first paragraph (see Figure 15.16). 7 When the page is loaded, this function will be called. It will cause a new para- graph to be inserted above the paragraph identified below this line, with the id, firstp. Figure 15.16 The DOM insertBefore() method. FORMAT reference_to_element.setAttribute(attributeName, value); reference_to_element.setAttribute(attributeName, value, boolean); // boolean 0 turns off case-sensitivity, 1 is on the default // Internet Explorer only EXAMPLE var headings = document.getElementsByTagName("h1") headings[0].setAttribute("id", "firsth1") EXPLANATION From the Library of WoweBook.Com ptg 638 Chapter 15 • The W3C DOM and JavaScript EXAMPLE 15.9 <html> <head><title>Create Elements and Attributes with the DOM</title> <style type="text/css"> p { font-style:arial; color:darkblue; font-size:18 } </style> </head> <body> <script type="text/javascript"> 1 window.onload=function(){ // Create three paragraphs with text 2 for(var i=1; i <= 3; i++){ 3 var aPara=document.createElement("p"); 4 var aBR = document.createElement("br"); 5 var theTXT1=document.createTextNode("Hello, world. "); var theTXT2=document.createTextNode("I hope you're enjoying this DOM stuff! "); var theTXT3=document.createTextNode("I am paragraph " + i +"."); 6 aPara.setAttribute("id","aPara" + i); //set id attribute for the p element document.body.appendChild(aPara); aPara.appendChild(theTXT1); aPara.appendChild(aBR); aPara.appendChild(theTXT2); aPara.appendChild(aBR); aPara.appendChild(theTXT3); } 7 alert(document.getElementById("aPara1")); } </script> </body> </html> EXPLANATION 1 When the page has completely been loaded, this anonymous function will be called. Its function is to create three paragraphs with unique ids and text (see Fig- ure 15.17). 2 The for loop will iterate three times to create the three paragraphs. 3 A reference to a new p element is created. From the Library of WoweBook.Com ptg 15.7 Modifying the DOM (Appending, Copying, and Removing Nodes) 639 15.7.6 DOM Review: Creating a Blog The next example, Example 15.10, is a program demonstrating how to use the DOM methods and properties we have covered thus far. The idea is to dynamically add new text entries, called blogs, into a Web page. The user will be presented with an area in which to write his or her blog. After the user clicks the “Add a blog” button, JavaScript will create a blog object and use DOM methods to define the structure of the new entry in the document. 1 Each blog entry will be appended to the previous one with the blog- ger’s name, the date the blog was posted, and the blog message. 4 A reference to a new br element is created. 5 A new text node is created to be placed in each paragraph. 6 A unique id attribute is set for each paragraph. 7 The getElementById() method returns a reference to the paragraph identified as “aPara1”. The alert method displays the value of the reference. Figure 15.17 Creating new elements and attributes with the DOM. 1. To save the blogs in a database or file, you will need a server-side program such as PHP or ASP.NET. EXPLANATION From the Library of WoweBook.Com ptg 640 Chapter 15 • The W3C DOM and JavaScript EXAMPLE 15.10 <html> <head><title>Creating a Blog</title> 1 <style type="text/css"> body{ background-color:#7fffd4;} div#div1{ background: white; border-width:1px; margin-left:20%; margin-right:20%; } p { margin-left:1%; font-family: arial;} </style> <script type="text/javascript"> 2 function BlogEntry(){ //Create a blog class var date; //Properties var message; var name; this.setDate=setDate; // Methods this.setBlogger=setBlogger; this.setMessage=setMessage; this.showBlog=showBlog; 3 function setDate(){ // Get the current date var d=new Date(); var year=d.getFullYear(); var month=d.getMonth() + 1; var day=d.getDate(); date=month + "/" + day + "/" + year; } 4 function setBlogger(nameVal){ name=nameVal; } function setMessage(messageVal){ message=messageVal; } 5 function showBlog(){ // Create HTML elements 6 var para = document.createElement("p"); var count=document.getElementsByTagName("p").length; // Get number of paragraphs 7 para.setAttribute("id","para" + count); // Set id for P // alert("There are " + count+ " paragraphs so far."); 8 var aBR = document.createElement("br"); var aBold = document.createElement("b"); 9 var divObj = document.getElementById("div1"); //Get a reference to the div From the Library of WoweBook.Com ptg 15.7 Modifying the DOM (Appending, Copying, and Removing Nodes) 641 10 divObj.appendChild(para); // Append a paragraph // Create nodes 11 var txt1=document.createTextNode("Posted by "+ name + " on ") var txt2=document.createTextNode(date); var txt3=document.createTextNode(message); 12 para.appendChild(txt1); 13 para.appendChild(txt2); aBold.appendChild(aBR); para.appendChild(aBold); aBold.appendChild(txt3); para.appendChild(aBold); 14 // alert(document.getElementById("para" +count).innerHTML); } 15 } // End class 16 function addBlog(){/* Add a blog entry using the DOM and get form data */ 17 message=document.getElementById("text").value; bloggername=document.getElementById("name").value; 18 var blog = new BlogEntry(); // Create a new blog object blog.setMessage(message); // Call object’s methods blog.setBlogger(bloggername); blog.setDate(); blog.showBlog(); } </script> </head> <body> <div align="center"> <img src="images/sunny.gif"> <img src="images/rain.gif"> <img src="images/partlycloudy.gif"> <img src="images/mostlycloudy.gif"> <img src="images/snow.gif"> </div> <h2 align="center">MoodyWedderBlog</h2> 19 <div id="div1"> </div > <br /> <div align="center"> <form method="post"> Enter your name (optional) <br /> <input type="text" id="name" /> <br /><br /> 20 <textarea id="text" name="text" rows="5" cols="40" onfocus="this.value=''"> </textarea><br /> Continues EXAMPLE 15.10 (CONTINUED) From the Library of WoweBook.Com ptg 642 Chapter 15 • The W3C DOM and JavaScript 21 <input type="button" value="Add a blog" onclick="addBlog();"/> </form> </div> </body> </html> EXPLANATION 1 This is the CSS style sheet for the page. 2 The function BlogEntry() defines a class consisting of the properties and methods for each new blog object that is created. 3 This method will get and format the current date with JavaScript’s Date() con- structor. It will be assigned to the date property of the object. 4 These next two methods will set the properties for the name of the blogger and the message the blogger typed into the form. 5 The showBlog() method is where we make good use of the DOM by creating ele- ments and text nodes. Each blog message will be placed in a paragraph appended to a div container. It will contain the blogger name and date on one line and the blogger’s message in bold text on the next lines. Every time a new blog is entered it will be appended in a paragraph to the previous paragraph. 6 A new paragraph element is created and a reference to it is assigned to para. 7 A unique id attribute is set for each paragraph after it is created. Every time a new paragraph is added the document.getElementsByTagName(“p”) method returns the number of p elements in the document, causing the count to go up by one. This count value is concatenated to the string “para” producing a new id for each new paragraph created on line 6. 8 A reference to an HTML br (break line) element is created and assigned to aBR. On the next line, a reference to an HTML b (bold) element is created. 9 The document.getElementById() method returns a reference to a div object identi- fied as div1 on line 19. This is where the paragraphs will be added and the blog messages displayed. 10 Now a p element (paragraph) is appended to the div object. 11 Three text nodes are created with values that will be inserted into the paragraph. The properties of the blog object, name, date, and message, contain the text values that will be assigned to the text nodes. 12 The text for the paragraph is now appended as a child node. 13 The next line of text is appended followed by the br element and the b element. 14 This alert(), when uncommented, will display the text (innerHTML) for each paragraph after it has been created, for example: Posted by Ellie Quigley on 3/21/2010<b><br>This is a hazy day and I'm in a hazy mood.</b> 15 The BlogEntry class ends here. EXAMPLE 15.10 (CONTINUED) From the Library of WoweBook.Com ptg 15.7 Modifying the DOM (Appending, Copying, and Removing Nodes) 643 16 The function addBlog() is a user-defined function, not part of the class. Its func- tion is to create a new blog object and assign it properties. 17 The form data (the blogger’s name and blog message) is retrieved with the document.getElementById() method. 18 An instance of a new BlogEntry object is created and a reference to it is assigned to the variable, blog. The methods for the object are called to set the properties for the blog object. 19 After setting up all the weather images, this is the div container where the blog messages will be stored and displayed. 20 The user will write his or her blog in a textarea input device. After writing the mes- sage, if the user leaves the text area and then clicks in the box, the onfocus event handler will be triggered and the box will be cleared by setting its value to an emp- ty string. 21 When the user clicks this button, the onclick event hander will call the addBlog() function to create a new blog object and set its properties with the form data re- trieved on line 17. The results are shown in Figures 15.18 and 15.19. Figure 15.18 Before adding a blog entry. EXPLANATION ( CONTINUED) From the Library of WoweBook.Com ptg 644 Chapter 15 • The W3C DOM and JavaScript 15.7.7 Creating a Table with the DOM Creating a table with the DOM can be a little confusing to say the least. Just as we have seen in previous examples, the DOM requires two steps: first, to create an empty element with the createElement() method, and then to insert the element into the document tree with the appendChild() or insertChild() method. That means for the table element, the table heading, captions, rows and table data, and so on. you must create an empty ele- ment and then place it in the tree. Forgetting a step will lead to a partial table or an empty page. Using a DOM inspector can be very helpful when laying out a table, as shown in Figure 15.20. Firefox does not require either a tBody or a tFoot. Internet Explorer requires that you create a tBody element and insert it into the table when using the DOM. Without it, you will get a blank page. Because you are manipulating the document tree directly, Internet Figure 15.19 The blog entries are appended as they are added. From the Library of WoweBook.Com . </style> <script type="text /javascript& quot;> 1 function insertMessage() { 2 var newPara = document.createElement("p"); 3 var newText = document.createTextNode("I am. type="text /javascript& quot;> 1 window.onload=function(){ // Create three paragraphs with text 2 for(var i=1; i <= 3; i++){ 3 var aPara=document.createElement("p"); 4 var aBR = document.createElement("br"); 5. document.createElement("br"); 5 var theTXT1=document.createTextNode("Hello, world. "); var theTXT2=document.createTextNode("I hope you're enjoying this DOM stuff! "); var theTXT3=document.createTextNode("I

Ngày đăng: 04/07/2014, 02:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan