1. Trang chủ
  2. » Công Nghệ Thông Tin

Học JavaScript qua ví dụ part 74 pps

9 187 0

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 9
Dung lượng 1,08 MB

Nội dung

ptg 15.7 Modifying the DOM (Appending, Copying, and Removing Nodes) 653 15.7.9 Removing a Node If you want to dynamically remove a post from a blog or an ingredient from an online recipe, it can be done with the DOM. To delete an element or node from the DOM tree, we use the removeChild() method. This method must be called from the parent node because you will be removing a child. It takes a reference to the child it will remove as its only argument. The following examples demonstrate how to dynamically remove nodes with JavaScript and the DOM. The first example, Example 15.15, removes a div and its contents; the second example, Example 15.16, removes paragraphs. 4 A reference to a new div is returned. 5 The cloned table is appended to the div just below the original table (see Figure 15.26). 6 This is the div container for the cloned table. Figure 15.26 Cloning a table with a unique id. EXPLANATION ( CONTINUED) From the Library of WoweBook.Com ptg 654 Chapter 15 • The W3C DOM and JavaScript FORMAT removeChild(referenceToChild) EXAMPLE parentDiv1.removeChild(div2); EXAMPLE 15.15 <html> <head><title>Removing a Child with the DOM</title> <script type="text/javascript"> 1 function removeDiv() { 2 var divMid = document.body.getElementsByTagName("div")[1]; 3 divMid.parentNode.removeChild(divMid); // Remove the middle div // alert((document.body.getElementsByTagName("div")).length // + " divs left"); prints 2 } </script> </head> <body onload="removeDiv()"> 4 <div>this is div1</div> 5 <div>this is div2</div> 6 <div>this is div3</div> </body> </html> EXPLANATION 1 The function called removeDiv() will remove a div element from the DOM tree. 2 The getElementsByTagName() method returns a reference to the second div tag in the document. The [1] index is applied to the <div> reference returned by getEle- mentsByTagName(), and retrieves the second div. [0] would be the first div in the list of <div> tags. 3 Using the reference to the second <div>, we go to the parent <div> and remove its child, the second div (see Figure 15.27). 4 Three divs are defined in this document. From the Library of WoweBook.Com ptg 15.7 Modifying the DOM (Appending, Copying, and Removing Nodes) 655 Figure 15.27 A div container is removed. EXAMPLE 15.16 <html> <head><title>Delete an Element with the DO</title> <style type="text/css"> p { font-style:arial; color:darkblue; font-size:18 } </style> <script type="text/javascript"> 1 function remove(f){ 2 for(var i=0; i<f.choice.length; i++){ 3 if(f.choice[i].checked){ //Find the paragraph that was checked 4 var p_element=document.getElementById(f.choice[i].value); 5 document.body.removeChild(p_element) } } } </script> </head> <body> <script type="text/javascript"> // Create three paragraphs with text 6 for(var i=1; i <= 3; i++){ var aPara=document.createElement("p"); var aBR = document.createElement("br"); var aTXT1=document.createTextNode("Hello, world. "); var aTXT2=document.createTextNode("I really don't want to be deleted! "); var aTXT3=document.createTextNode("I am paragraph " + i); 7 aPara.setAttribute("id","aPara" + i); document.body.appendChild(aPara); aPara.appendChild(aTXT1); //Put paragraph in the doc aPara.appendChild(aBR); Continues From the Library of WoweBook.Com ptg 656 Chapter 15 • The W3C DOM and JavaScript aPara.appendChild(aTXT2); aPara.appendChild(aBR); aPara.appendChild(aTXT3); } </script> <form> Which paragraph do you want to remove? <br /> 8 <input type="radio" name="choice" value="aPara1">Paragraph 1 /><br /> <input type="radio" name="choice" value="aPara2">Paragraph 2 /><br /> <input type="radio" name="choice" value="aPara3">Paragraph 3 /><br /> <input type=button value="click for paragraph to remove" 9 onClick="remove(this.form);"/> </form> </body> </html> EXPLANATION 1 This user-defined function is responsible for removing a paragraph based on the user’s choice. The parameter, f, is a reference to the form object passed when the button was clicked on line 9. 2 The for loop will iterate three times, one for each radio button. 3 The radio button’s property, checked, returns true for the button if it was selected. 4 Based on the choice of the user (i.e., the radio button that was checked), the ge- tElementById() method will return a reference to the value attribute of the radio button that happens to be the unique id of the paragraph. 5 The paragraphs are children of the body element. Now that we have a reference to the paragraph, it can be removed from the body of the document with the rem- oveChild() DOM method. 6 This for loop cycles three times. For each iteration of the loop a new paragraph is dynamically created using the DOM. 7 Each paragraph is assigned a unique id attribute to be used by JavaScript to get a reference to the paragraph to be removed. 8 The user can click a radio button to remove one of the paragraphs. 9 When the user clicks this button, a reference to this form, this.form, is sent to the function called remove(). This process is shown in Figures 15.28, 15.29, and 15.30. EXAMPLE 15.16 (CONTINUED) From the Library of WoweBook.Com ptg 15.7 Modifying the DOM (Appending, Copying, and Removing Nodes) 657 Figure 15.28 Three paragraphs have been created. Figure 15.29 The user clicks on paragraph 2 for removal. From the Library of WoweBook.Com ptg 658 Chapter 15 • The W3C DOM and JavaScript 15.7.10 Scrolling with the Nodes In the following example, all three layers of a a Web page are represented: the HTML content layer, the CSS presentation layer, and the JavaScript behavioral layer. By using the getElementById() method and a little node knowledge, a scrolling marquee is created in Example 15.17. In Chapter 10, Example 10.11 we saw scrolling in the window’s status and title bar. Now we can scroll within the body of the document. The program creates a message that will continuously scroll across the screen. The original message is placed within a <div> container. By first identifying the HTML div element—getElement- ById()—JavaScript can then reference its child node, which is the text of the message (firstChild). This is depicted in Figure 15.31. Figure 15.30 Paragraph 2 has been removed. Figure 15.31 Referencing a child node requires first identifying the div element. div text parent node child node From the Library of WoweBook.Com ptg 15.7 Modifying the DOM (Appending, Copying, and Removing Nodes) 659 EXAMPLE 15.17 <html> <head><title>Scrolling Text</title> <style type="text/css"> 1 #div1 { background-color:darkgreen; color: white; font-family:courier; font-weight: bold; position:absolute; border-style:groove; border-color:white; padding-left:10px; top:20px; left:10px; 2 width: 595px; height: 6%; 3 overflow: hidden; } 4 img { position: absolute; top: 10px;left:60px; border-style:solid;border-color:"darkgreen";} body { background-color:#669966;} </style> <script type="text/javascript"> 5 /*Modification of text box marquee by Dave Methvin, Windows Magazine */ 6 var scroll_speed = 200; // 200 milliseconds var chars = 1; var divElement; 7 window.onload=function() { divElement=document.getElementById("div1"); } 8 function scroller() { 9 window.setTimeout('scroller()',scroll_speed); 10 var msg=divElement.firstChild.nodeValue; 11 divElement.firstChild.nodeValue = msg.substring(chars) + msg.substring(0,chars); } 12 scroller(); </script> </head> <body> <img src="BubyanIsland.JPG" width="450" length="500"> 13 <div id="div1"> The latest news from Baghdad is not good tonight. Sand and rain are hindering our troops. The number of refugees continues to increase in the north </div> </body> </html> From the Library of WoweBook.Com ptg 660 Chapter 15 • The W3C DOM and JavaScript EXPLANATION 1 An ID selector is defined with a style for the div element on line 13. 2 The size of the div container is defined. 3 If the text within the div container will not fit within the dimensions of the box, the overflow property will adjust it to fit. 4 The image is fixed at this absolute position on the screen and has a dark green, solid border. 5 The scroller() routine (line 8), modified from the original, was found at the Java Planet Web site and submitted by Dave Methvin. (Thank you Dave, wherever you are!) 6 The initial values used for the scroller() function are assigned values. One is the speed for the timer, the other the value of an argument to the substr() method. 7 This anonymous function is called after the document has been loaded. Its pur- pose is to get a reference to the div element. The getElementById() method returns a reference to the div element. 8 The function called scroller() is defined. Its function is to cause the text found in the <div> container to scroll continuously from the right side of the container. 9 The window’s setTimeout() method is used to call the scroller() function every 200 milliseconds (.2 seconds). It’s the timer that creates the action of actually scrolling. 10 The div element is a parent node. It has a child node. The value of its first child, divElement.firstChild.nodeValue, is the textual content of the message; that is, the text found between the <div></div> tags. The variable msg gets the value of the child node. 11 The value returned by msg.substr(1) is “he latest news from Baghdad is not good to- night. Sand and rain are hindering our troops. The number of refugees continues to in- crease in the north ” Notice that the first character in the message has been re- moved. The next substring method will return the first character— substring(0,1)—and append it to the first value resulting in “he latest news from Baghdad is not good tonight. Sand and rain are hindering our troops. The number of refugees continues to increase in the north T”. All of this is assigned back to the val- ue of the child node. In 200 milliseconds, the scroller() function is called again, and the message becomes “e latest news from Baghdad is not good tonight. Sand and rain are hindering our troops. The number of refugees continues to increase in the north Th”, and so on. 12 The scroller() function is called for the first time here. 13 The <div> tags contain the text of the message that will be scrolled. Its id, “div1”, defines the CSS style that will be used, and is the unique identifier that will be used by JavaScript to get a reference to it. See the output in Figure 15.32. From the Library of WoweBook.Com ptg 15.8 Event Handling and the DOM 661 15.8 Event Handling and the DOM 15.8.1 The HTML Inline Way We have been using event handlers like onClick, onSubmit, onMouseOver, throughout this text. In fact, Chapter 13, “Handling Events,” described in detail all of the different event handlers and how to use them. They are the oldest and simplest way that is browser compatible. The following example uses the onClick handler as an attribute of the button element. When the user clicks the button, the function movePosition() will be called. <input type="button" value="move text" onClick="movePosition()"/> But using this type of handler violates the principle of separation of the layers; that is, the separation of markup from JavaScript. 15.8.2 The Scripting Way To keep the markup and the JavaScript separate, the JavaScript provided a way for pro- grammers to apply properties to any object in the HTML tree. In the following example, the onLoad event property is applied to the window object so that when the document has completed loading the function assigned to that object will be triggered. In this example the background color will be changed to light green. See Chapter 13 for details if you need to be refreshed on this traditional model for handling events. Figure 15.32 A scrolling marquee continues to print news across the image. From the Library of WoweBook.Com . the layers; that is, the separation of markup from JavaScript. 15.8.2 The Scripting Way To keep the markup and the JavaScript separate, the JavaScript provided a way for pro- grammers to apply. DOM and JavaScript 15.7.10 Scrolling with the Nodes In the following example, all three layers of a a Web page are represented: the HTML content layer, the CSS presentation layer, and the JavaScript. <head><title>Removing a Child with the DOM</title> <script type="text /javascript& quot;> 1 function removeDiv() { 2 var divMid = document.body.getElementsByTagName("div")[1]; 3

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

TỪ KHÓA LIÊN QUAN