簡體   English   中英

將文本區域的值應用於變量時發生TypeError

[英]TypeError when applying a textarea's value to a variable

JavaScript的

var textarea = document.getElementById("textarea").value;

HTML

<textarea id="textarea" cols="100" rows="10">du hello!</textarea>

TypeError:表達式'document.getElementById("textarea")' [null]不是對象。

此錯誤表明它找不到ID為“ textarea”的元素。 因此,此getElementById操作的結果為null ,並且您無法訪問null .value ,因為它沒有任何屬性。

根本原因是在搜索時不存在id為“ textarea”的元素。 您可能在某個地方輸入錯誤,或者腳本在元素不存在時運行(尚未)。 如果腳本位於標頭中,則需要這樣編寫:

document.ready = function () {
    ... script here ...
}

這將延遲執行,直到文檔准備就緒並且所有元素都存在。

如果您使用的是諸如tinymce之類的所見即所得編輯器 ,否則。 。的document.getElementById( “文字區域”)值; 他們有自己的方法來獲取數據將無法正常工作。

<script type="text/javascript">
  function test(name){
    var textarea = document.getElementById("textarea").value;
    alert(textarea)
  }
</script>

<textarea id="textarea" cols="100" rows="10">du hello!</textarea>
<a href="javascript:void(0)" onclick="javascript:test('this is just testing')">Test TextArea</a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM