输入到对象

时间:2018-02-03 14:12:11

标签: javascript

我的问题是:如何将 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;}

2 个答案:

答案 0 :(得分:0)

做你说的话:

function updateFirstName() {
 person.firstName = document.getElementById("userInput").value; 
 document.getElementById("demo").innerHTML = person.fullName();
}

答案 1 :(得分:0)

  • 您可以将事件input添加到输入字段。
  • 将输入的输入(firstName)设置为对象person

查看此代码段:

&#13;
&#13;
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;
&#13;
&#13;

请参阅?对象人员正在自动更新。

资源