JvaScript--使用js添加數據,點擊按鈕,將內容放入表格中



題目要求:

創建一個Student類,有name、age屬性和方法showInfo(),
在頁面上顯示:
<p>姓名&nbsp;&nbsp;|&nbsp;&nbsp;年齡</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>


運行結果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章