2017-09-25 110 views
0

應該說Bob Miller在控制檯爲什麼不通過Console.log結果?

但是,相反,它說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> 
+2

getElementsByClassName方法返回HTMLDomArray。您需要執行 'document.getElementsByClassName('className')[0] .value',因爲該數組沒有值 – Gibolt

回答

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);
<input placeholder='Enter First Name' value='Bob' class='firstName'> 
 
<input placeholder='Enter Last Name' value='Miller' class='lastName'>

相關問題