從 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 編輯器中的開啟即時伺服器選項。

以下是輸出。當您單擊滑鼠並放置箭頭鍵時,您將獲得以下輸出。

快照如下 -


更新於: 16-Jul-2020

2 千+ 次瀏覽

開啟你的事業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.