我的问题是:如何将 var x
(基本上是用户输入数据)迁移到 var person
,以便用户可以更改person.firstName
通过将数据输入<input type="text" id="userInput" value="">
元素。我是JS概念的新手,所以我会感激任何帮助。谢谢。
var person = {
firstName : "John",
lastName : "Doe",
age : 30,
fullName : function() {
return "My name is " + this.firstName + " " + this.lastName + " I am " + this.age + " years old";
}
};
document.getElementById("demo").innerHTML = person.fullName (); // Result: My name is John Doe I am 30 yers old
/* Input */
function myFunction() {
var x = document.getElementById("userInput").value;
document.getElementById("demo").innerHTML = x;}
答案 0 :(得分:0)
做你说的话:
function updateFirstName() {
person.firstName = document.getElementById("userInput").value;
document.getElementById("demo").innerHTML = person.fullName();
}
答案 1 :(得分:0)
input
添加到输入字段。person
。查看此代码段:
var person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
return "My name is " + this.firstName + " " + this.lastName + " I am " + this.age + " years old";
}
};
document.getElementById("demo").innerHTML = person.fullName();
/* Input */
function myFunction() {
var x = document.getElementById("userInput").value;
person.firstName = x;
document.getElementById("demo").innerHTML = person.fullName();
}
document.getElementById("userInput").addEventListener('input', myFunction);
&#13;
<span id='demo'></span>
<p>User Input</p>
<input type="text" id="userInput" value="">
&#13;
请参阅?对象人员正在自动更新。