使用javascript原型,需要动态添加div onclick [英] Using javascript prototype, need to dynamically add div onclick
本文介绍了使用javascript原型,需要动态添加div onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
(我在javascript中学习原型..)
我需要在div上动态添加学生详细信息,并在单击按钮(添加更多)时使用javascript原型继续添加更多内容。
(I am studying prototype in javascript..) I need to dynamically add student details on a div and keep adding more by using javascript prototype when a button(Add More) is clicked.
到目前为止,这是我的代码:
So far here's my code:
Javascript:
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>
我的小提琴: http://jsfiddle.net/2TMuB/
我不知道如何动态创建新的学生对象显示它们。
Am getting stuck where i don't know how to create new student objects dynamically and to display them.
推荐答案
不要将addStudent函数设置为原型。
Do not make addStudent function to 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原型,需要动态添加div onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文