javascript - 我正在尝试制作代码编辑器,但结果框中没有任何内容
问题描述
我正在尝试向我的网站添加代码编辑器,但结果框中没有出现任何内容。
我尝试使用 .innerHTML 提取代码,并将其放入结果框中,但没有出现任何内容。
<!DOCTYPE html>
<body>
<textarea id='codeBox'>
<!DOCTYPE html>
<html>
<body>
</body>
</html>
</textarea>
<div id='result'></div>
<button onclick='run()' style='text-align: center;'>Run</button>
<style>
body {
display: grid;
grid-columns: 50% 50%;
}
#codeBox {
grid-column: 1;
height: 500px;
overflow: scroll;
}
#result {
grid-column: 2;
height: 500px;
overflow: scroll;
border: 1px solid gray;
}
</style>
<script>
let codeBox = document.getElementById('codeBox').innerHTML;
let result = document.getElementById('result').innerHTML;
function run() {
result.innerHTML = codeBox.innerHTML;
};
</script>
</body>
解决方案
您应该使用 textarea 值,并且每次单击运行时都应该读取该值,而不仅仅是在加载页面时。
function run() {
result.innerHTML = document.getElementById('codeBox').value;
};
body {
display: grid;
grid-template-columns: 50% 50%;
}
#codeBox {
grid-column: 1;
height: 500px;
overflow: scroll;
}
#result {
grid-column: 2;
height: 500px;
overflow: scroll;
border: 1px solid gray;
}
<textarea id='codeBox'>
<!DOCTYPE html>
<html>
<body>
It works!
</body>
</html>
</textarea>
<div id='result'></div>
<button onclick='run()' style='text-align: center;'>Run</button>