为什么不管Console.log结果?

时间:2017-09-25 07:49:59

标签: javascript logging console

它应该在控制台中说Bob Miller

但它代之以Undefined Undefined

如果有人帮我解决这个问题,我真的很感激。

<body bgcolor='000000'>
   <center>
       <input placeholder='Enter First Name' value='Bob' class='firstName'>
       <input placeholder='Enter Last Name' value='Miller' class='lastName'>
   </center>
</body>
<script>
   firstname = document.getElementsByClassName('firstName').value;
   lastname = document.getElementsByClassName('lastName').value;
   result = firstname + ' ' + lastname;
   console.log(result);
</script>

1 个答案:

答案 0 :(得分:4)

document.getElementsByClassName方法返回一个像对象这样的数组,而不是单个数组。您需要访问该对象中的[0]th项作为访问带索引的数组,然后获取其值。同时使用var/let/const关键字明确声明您的变量。

&#13;
&#13;
var firstname = document.getElementsByClassName('firstName')[0].value;
// ---------------------------------------------------------^^^------
var lastname = document.getElementsByClassName('lastName')[0].value;
// -------------------------------------------------------^^^------
var result = firstname + ' ' + lastname;
console.log(result);
&#13;
<input placeholder='Enter First Name' value='Bob' class='firstName'>
<input placeholder='Enter Last Name' value='Miller' class='lastName'>
&#13;
&#13;
&#13;