它应该在控制台中说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>
答案 0 :(得分:4)
document.getElementsByClassName方法返回一个像对象这样的数组,而不是单个数组。您需要访问该对象中的[0]th
项作为访问带索引的数组,然后获取其值。同时使用var/let/const
关键字明确声明您的变量。
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;