即使在给出值之后,对象也会给出空值

时间:2017-08-25 11:43:56

标签: javascript

window.onload = function() {

  var Employee = function(name, bd) {
    this.name = name;
    this.bd = bd;
    this.age = function() {
      2017 - this.bd;
    }
  }

  var empName = document.getElementById("name").value;
  var empBday = document.getElementById("bday").value;

  var empList = new Employee(empName, empBday);

  var Btn = document.getElementById('add').addEventListener('click', function() {
    console.log(empList);
  });
}
<input type="text" id="name" value=""></input>
<input type="text" id="bday" value=""></input>
<button id="add">Add</button>

即使我输入了一些值,然后我将Console.log中的对象称为“emplist”,但我只得到Employee {name: "", bd: "", age: ƒ}

3 个答案:

答案 0 :(得分:5)

仅在单击按钮后创建对象:

var Employee = function(name, bd) {
    this.name = name;
    this.bd = bd;
    this.age = function() {
        2017 - this.bd;
    }
}

window.onload = function () {
    document.getElementById('add').addEventListener('click', function(){
        var empName = document.getElementById("name").value;
        var empBday = document.getElementById("bday").value;

        var empList = new Employee(empName, empBday);
        console.log(empList);
    });
}

答案 1 :(得分:4)

您在窗口onload中为对象分配值。因此,分配空值是因为输入元素在默认情况下具有空值

将其更改为

&#13;
&#13;
window.onload = function () {


var Btn = document.getElementById('add').addEventListener('click', function(){
    var Employee = function(name, bd){
    this.name = name;
    this.bd = bd;
    this.age = function(){
        2017 - this.bd;
    }
}

var empName = document.getElementById("name").value;
var empBday = document.getElementById("bday").value;

var empList = new Employee(empName, empBday);
console.log(empList);
});
}
&#13;
<html>
    <head>
        <title>Employee Details</title>
        <script src="script.js"></script>
    </head>
    <body>
        <input type="text" id="name" value=""></input>
        <input type="text" id="bday" value=""></input>
        <button id="add">Add</button>
    </body>
</html>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

您需要像这样添加处理程序更改事件:

<html>
    <head>
        <title>Employee Details</title>
        <script src="script.js"></script>
    </head>
    <body>
        <input type="text" id="name"></input>
        <input type="text" id="bday"></input>
        <button id="add">Add</button>
    </body>
</html>
df['x'] = df.apply(lambda x: tuple(sorted(x)), axis=1)
df = df.drop_duplicates('x')
del df['x']