JavaScript 第四章 作業
阿新 • • 發佈:2018-12-19
1.使用JavaScript建立一個物件student,表示一個學生物件,新增屬性:姓名,年齡,自我介紹,新增方法:輸出該學生的姓名,年齡和自我介紹
實現程式碼如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <div id="div"></div> <script type="text/javascript"> var student = new Object(); student.name = "工藤新一"; student.age = 17; student.intro = "我叫工藤新一,我是一名高中二年級學生,我非常喜歡推理和足球!"; student.showIntro = function(){ var list = "姓名:" + this.name+"<br/>年齡:"+this.age+"<br/>自我介紹:"+this.intro; return list; } document.getElementById("div").style.lineHeight="35px"; document.getElementById("div").innerHTML=student.showIntro(); </script> </body> </html>
2.建立一個建構函式Student,新增屬性和方法,在方法中使用createElement()建立p標籤,使用innerHTML把姓名,年齡和自我介紹顯示在此p標籤中,使用return返回p標籤,使用new建立兩個學生物件,使用getElementById()和appendChild()把建立的學生物件資訊追加到頁面中去
實現程式碼如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="div"></div> <script type="text/javascript"> function Student(name, age, intro) { this.name = name; this.age = age; this.intro = intro; this.showIntro = showIntro; } function showIntro() { var p = document.createElement("p"); var list = "姓名:" + this.name + "<br/>年齡:" + this.age + "<br/>自我介紹:" + this.intro; p.innerHTML = list; return p; } var student1 = new Student("王小明", 16, "我是高中一年級的學生,身高1.8米,很帥,我喜歡學習語文和英語。"); var student2 = new Student("黃妞妞", 6, "我今年6歲了,常可愛,馬上就可以上小學了,就可能有好多好多的小朋友了。"); document.getElementById("div").appendChild(student1.showIntro()); document.getElementById("div").appendChild(student2.showIntro()); </script> </body> </html>
5.建立一個建構函式Animal使用繼承完成輸出動物的自我介紹
實現程式碼如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="div"></div> <script type="text/javascript"> function Animal(name, color, age) { this.name = name; this.color = color; this.age = age; } function inherit(name, color, age, leg) { Animal.call(this, name, color, age); this.leg = leg; } inherit.prototype = new Animal(); inherit.prototype.info = function() { var p = document.createElement("p"); var list = "我是一個" + this.color + "的" + this.name + ",我已經" + this.age + "歲了,我有" + this.leg + "條腿"; p.innerHTML = list; return p; }; var inherit1 = new inherit("小狗狗", "灰色", 1, 4); var inherit2 = new inherit("茶杯貓", "白色", 2, 4); var inherit3 = new inherit("母雞", "紅色", 1, 2); document.getElementById("div").appendChild(inherit1.info()); document.getElementById("div").appendChild(inherit2.info()); document.getElementById("div").appendChild(inherit3.info()); </script> </body> </html>