创建一个代码元素并将其附加到.codeblockdiv不创建代码标签?



所以我做了一个代码块,你可以编辑和创建一个新的代码块,但问题是,它没有创建code标签。这是我的代码:

<style>
html, body {
margin-top: 5px;
}
.codeblockDiv {
width: 50%;
}
.codeblock {
background: linear-gradient(to top, rgb(207, 207, 207) 16%, rgb(252, 252, 252) 79%);
border: 1px solid;
border-radius: 5px;
padding: 4px;
width: 50%;
display: inline-block;
outline: none;
}
.edit {
top: 0;
right: 300px;
position: absolute;
}
.cancel {
top: 0;
right: 350px;
position: absolute;
}
.new {
left: 9px;
top: 0;
position: absolute;
}
</style>
<body>
<button class="new" onclick="newCodeblock()">
New
</button>
<button class="edit" onclick="editCode()">
Edit
</button><br>
<code class="codeblock" id="codeBlock">
&lt;!DOCTYPE html&gt;<br>
&emsp;&lt;html&gt;<br>
&emsp;&emsp;&lt;head&gt;<br>
&emsp;&emsp;&emsp;&lt;meta charset&#61;&ldquo;UTF-8&rdquo;&gt;<br>
&emsp;&emsp;&emsp;&lt;title&gt;Example&lt;&sol;title&gt;<br>
&emsp;&emsp;&lt;&sol;head&gt;<br>
&lt;body&gt;<br>
&emsp;&lt;div&gt;<br>
&emsp;&emsp;&lt;p&gt;This is in a &lt;code&gt; tag&lt;&sol;p&gt;<br>
&emsp;&lt;&sol;div&gt;<br>
&lt;&sol;body&gt;<br>
&emsp;&lt;&sol;html&gt;
</code><br>
<script>
function editCode() {
var x = document.getElementById('codeBlock');
x.setAttribute("contenteditable", "true")
var y = document.createElement('button')
y.innerHTML = "Cancel";
y.className = "cancel";
document.body.appendChild(y);
y.addEventListener('click', function() {
x.setAttribute("contenteditable", "false")
y.remove()
})

}
function boldText(e) {
if (e.keyCode == 17 && e.keyCode == 66) {
let textBox = document.querySelector('.codeblock');
textBox.style.fontWeight = 'bold';
}
}
function newCodeblock() {
var z = document.createElement('code'); 
var h = document.createElement('button');
z.className = "codeblock";
z.innerHTML = "Write Here"
z.setAttribute("contenteditable", "true");
h.innerHTML = "Save";
h.addEventListener('click', function() {
z.setAttribute("contenteditable", "false");
h.remove();
})
document.querySelector('.codeblockDiv').appendChild(h);
document.querySelector('.codeblockDiv').appendChild(x);
}
</script>
<div class="codeblockDiv">

</div>
</body>
这里JSFiddle

您的newCodeblock函数引用了一个不存在的变量x

如果你改变

document.querySelector('.codeblockDiv').appendChild(x);

document.querySelector('.codeblockDiv').appendChild(z);

您的newCodeblock函数将成功运行

相关内容

  • 没有找到相关文章

最新更新