题目要求:
创建一个Student类,有name、age属性和方法showInfo(),
在页面上显示:
<p>姓名 | 年龄</p>
<div>
</div>
<input type="button" value="显示下一条数据" οnclick="show()" />
然后再div中使用js添加数据,每点击一下按钮就显示一条数据,(必须通过p元素去找div)
*其中要写一个函数show()用来调用Student类里面的showInfo()函数
function show() {
var stu = new Stdudent();
stu.showInfo();
}
完整代码如下:
<pre class="javascript" name="code"><!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function Student(name, age) {
this.name = name;
this.age = age;
}
Student.prototype.showInfo = function() {
var oP = document.getElementById("title");
var pNode = document.createElement("p");
var textNode = document.createTextNode(this.name + "\t|\t" + this.age);
pNode.appendChild(textNode);
oP.nextSibling.nextSibling.appendChild(pNode);
}
var count = 0;
var stu1 = new Student("张三", 13);
var stu2 = new Student("李四", 30);
var students = [stu1, stu2];
function show() {
if (count < 2) {
students[count++].showInfo();
}
}
</script>
</head>
<body>
<p id="title">姓名 | 年龄</p>
<div>
</div><!-- hahaha -->
<input type="button" value="显示下一条数据" οnclick="show()" />
</body>
</html>
运行结果: