從 JavaScript 中的 div 獲取值導致 undefined?
為此使用 document.getElementById().innerHTML。以下是 JavaScript 程式碼 -
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class='getValueFromDiv' id='getValue' contenteditable="true" onkeyUp='display()'
style="color: red"></div>
<script>
function display(){
var storedValue = document.getElementById('getValue').innerHTML.value="This is the
value";
console.log("The value is==="+storedValue);
}
</script>
</body>
</html>若要執行上述程式,儲存檔名 任何名稱.html(index.html),然後右鍵單擊該檔案,並選擇 VS Code 編輯器中的開啟即時伺服器選項。
以下是輸出。當您單擊滑鼠並放置箭頭鍵時,您將獲得以下輸出。
快照如下 -

廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP