gpt4 book ai didi

javascript - 使用javascript原型(prototype),需要动态添加div onclick

转载 作者:行者123 更新时间:2023-11-30 17:36:04 25 4
gpt4 key购买 nike

(我正在研究 javascript 中的原型(prototype)..)我需要在 div 上动态添加学生详细信息,并在单击按钮(添加更多)时使用 javascript 原型(prototype)继续添加更多信息。

到目前为止,这是我的代码:

Javascript:

function Student(name, age, department) {
this.name = name;
this.age = age;
this.department = department;
}

Student.prototype.addStudent = function() {
var s1 = new Student();
s1.name = document.getElementById('name').value;
s1.age = document.getElementById('age').value;
s1.department = document.getElementById('department').value;

};

这是我的 html:

 <!DOCTYPE html>
<html>
<head>
<title>Prototype_Student</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="../css/student_style.css"/>
</head>
<body>
<div>Student List</div>
Name:<input class="inputFields" id="name"/><br><br>
Age:<input class="inputFields" id="age"/><br><br>
Department:<input class="inputFields" id="department"/><br><br>
<button id="addMore" onclick="addStudent(name, age, department);">Add Student</button>
<script src="../js/student_main.js"></script>
</body>
</html>

我的 fiddle :http://jsfiddle.net/2TMuB/

我不知道如何动态创建新的学生对象并显示它们。

最佳答案

不要将 addStudent 函数作为原型(prototype)。

function Student(name, age, department) {
this.name = name;
this.age = age;
this.department = department;
}

Student.prototype.display = function() {
document.write("Name: " + this.name + ", age:" + this.age + "<br>")
};

function addStudent() {
var s1 = new Student();
s1.name = document.getElementById(name);
s1.age = document.getElementById(age);
s1.department = document.getElementById(department);
}

关于javascript - 使用javascript原型(prototype),需要动态添加div onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22034243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com