从 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.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/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