为什么输入值显示不正确?

时间:2016-03-09 16:01:27

标签: javascript html

<body>
<div class="container">
    <div class="form-group">
        <label for="firstNameInput">Firstname:</label>
        <input type="text" class="form-control" id="firstNameInput" name="firstNameInput">

        <label for="lastNameInput">Lastname:</label>
        <input type="text" class="form-control" id="lastNameInput" name="lastNameInput">            
    </div>

    <button class="btn btn-info" onclick="showName()">Submit</button>
    <p id="demo"></p>
</div>

<script type="text/javascript">
    var person = {
        firstName:document.getElementById('firstNameInput').value,
        lastName:document.getElementById('lastNameInput').value,
        fullName: function () {return this.firstNameInput + ", " + this.lastNameInput;}
    };

    function showName() {
        document.getElementById('demo').innerHTML = person.fullName();
    };
</script>

为什么输入值显示不正确? //现在的结果是==&gt; undefined,undefined 请帮我找错我的代码!

3 个答案:

答案 0 :(得分:2)

首先,您使用的变量名称不正确

return this.firstNameInput + ", " + this.lastNameInput;

this.firstName而非this.firstNameInput

下一步:如果您在函数外部声明person,则firstNamelastName将具有null值,因为输入元素在页面加载时没有值。< / p>

您必须在函数内声明person,以便在按钮点击时将输入字段中的值分配给firstNamelastName

<body>
<div class="container">
    <div class="form-group">
        <label for="firstNameInput">Firstname:</label>
        <input type="text" class="form-control" id="firstNameInput" name="firstNameInput">

        <label for="lastNameInput">Lastname:</label>
        <input type="text" class="form-control" id="lastNameInput" name="lastNameInput">            
    </div>

    <button class="btn btn-info" onclick="showName()">Submit</button>
    <p id="demo"></p>
</div>

<script type="text/javascript">
    

    function showName() {
      
      var person = {
        firstName: document.getElementById('firstNameInput').value,
        lastName: document.getElementById('lastNameInput').value,
        fullName: function () {return this.firstName + ", " + this.lastName;}
        };
      
        document.getElementById('demo').innerHTML = person.fullName();
    };
</script>

答案 1 :(得分:0)

初始化person对象时,直接询问输入字段的值。发生这种情况时,用户没有时间插入值。您应该做的是询问yDomain: [0, maxY] // maxY being whatever you want your max y value to be函数中的值。见这个例子:

fullName

答案 2 :(得分:0)

我认为如果你想获得ements输入值,应该在ShowName函数中声明var person。有&#39;这可能是一种更清洁的方式...