我正在尝试一些事情来学习如何使用构造函数和对象。我想创建一个页面来显示使用Javascript中的构造函数和对象来自文本字段的输入。当我单击保存时,它会在HTML页面上显示 [object Object] 。我做了一些尝试,但是失败了。
function Persons(name, age){
this.name = name;
this.age = age;
}
var button = document.querySelector('#save');
function showPerson4(){
var name = document.querySelector("#name");
var age = document.querySelector("#age");
var person4 = new Persons();
person4.name = name;
person4.age = age;
document.querySelector("#person4").innerHTML = person4;
}
button.addEventListener("click", function (ev) {
ev.preventDefault();
showPerson4();
},false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Show person</title>
</head>
<body>
Name: <input type="text" id="name" name="name" placeholder="Enter your name"><br>
Age: <input type="text" id="age" name="age" placeholder="Enter your age">
<button id="save" name="save">Save</button>
<p id="person4" class="person4"></p>
<script src="js/opdracht1.js"></script>
</body>
</html>
答案 0 :(得分:3)
您正在选择元素,而不是值。更新到:
var name = document.querySelector("#name").value;
var age = document.querySelector("#age").value;
我已经使用prototype.toString
覆盖了toString()
的{{1}}方法
Persons
function Persons(name, age){
this.name = name;
this.age = age;
}
// override the persons.toString
Persons.prototype.toString = function personToString()
{
return 'Name: ' + this.name + ', Age: ' + this.age;
}
var button = document.querySelector('#save');
function showPerson4(){
var name = document.querySelector("#name").value;
var age = document.querySelector("#age").value;
var person4 = new Persons(name, age);
// call toString()
document.querySelector("#person4").innerHTML = person4.toString();
}
button.addEventListener("click", function (ev) {
ev.preventDefault();
showPerson4();
},false);
答案 1 :(得分:0)
您刚刚犯了两个错误
1)您为输入控件本身分配了变量名称和年龄,而不是其值
var name = document.querySelector("#name").value;
var age = document.querySelector("#age").value;
2)要以html显示Javascript对象,您必须将其转换为字符串JSON.stringify()可以解决问题
function Persons(name, age){
this.name = name;
this.age = age;
}
var button = document.querySelector('#save');
function showPerson4(){
//get the value from inputs
var name = document.querySelector("#name").value;
var age = document.querySelector("#age").value;
var person4 = new Persons();
person4.name = name;
person4.age = age;
//Stringify results for viewing object in html
document.querySelector("#person4").innerHTML = JSON.stringify(person4);
}
button.addEventListener("click", function (ev) {
ev.preventDefault();
showPerson4();
},false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Show person</title>
</head>
<body>
Name: <input type="text" id="name" name="name" placeholder="Enter your name"><br>
Age: <input type="text" id="age" name="age" placeholder="Enter your age">
<button id="save" name="save">Save</button>
<p id="person4" class="person4"></p>
<script src="js/opdracht1.js"></script>
</body>
</html>