使用 JavaScript 从 div 获取值,结果未定义?

javascriptweb developmentobject oriented programming更新于 2025/8/21 14:36:17

使用 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 restoredValue = document.getElementById('getValue').innerHTML.value="This is the
      value";
      console.log("The value is==="+storedValue);
   }
</script>
</body>
</html>

要运行上述程序,请保存文件名 anyName.html(index.html),右键单击该文件并选择 VS Code 编辑器中使用实时服务器打开选项。

以下是输出。当您单击鼠标并放置箭头键时,您将获得以下输出。

The snapshot is as follows −


相关文章


有用资源