我學習到Java腳本,並嘗試運行這段代碼的用戶在輸入文本輸入任何值,然後輸入的數據在「P」標籤,但是當得到打印我使用的調試,看看那裏的代碼出了錯它彈出我與以下錯誤JavaScript錯誤無法從<input>標籤獲取輸入
Uncaught TypeError: Cannot read property 'value' of undefined
代碼:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var a = document.getElementById("txt_1")[0].value;
document.getElementById("demo").innerHTML = a;
}
</script>
</head>
<body>
<form>
<input type="text" id="txt_1" name="txt_1">
<input type="button" onclick="myFunction()" value="Click me">
</form>
<p id="demo"></p>
</body>
</html>
感謝您的幫助,你可以告訴我,我們在什麼具體的使用「索引」,即** [0] .value **在JavaScript中? –
@MehulChachada建立索引,你可以使用''數組''和'數組'類似的對象。所以如果你有很多'p'元素並且想要獲取所有元素的getElementsByTagName'函數,它會返回一個''類似''對象的數組。對於''數組'類似的對象中的每個元素,您可以調用'[]'並傳遞該對象中項目的索引 –