概述:我有一个可编辑的 div 部分。在 div 下方,有一个创建 span 元素的按钮,在 span 元素中插入文本“tag”,最后将 span 元素附加到该可编辑的 div 中
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
#sample-div
{
border-style: solid;
border-width: 1px;
border-color: black;
height:100px;
overflow: auto;
}
</style>
<script type="text/javascript">
function addTags()
{
var tag = document.createElement("span");
tag.className = "tag"
tag.innerHTML = "tag";
$('#sample-div').append(tag);
}
</script>
</head>
<body>
<div id="sample-div" contenteditable="true"></div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
</body>
</html>
观察:我点击按钮,span 元素按预期添加到 div
<div id="sample-div" contenteditable="true">
<span class="tag">tag</span>
</div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
但是,在我开始在 div 中键入内容后,我注意到以下内容:
<div id="sample-div" contenteditable="true">
<span class="tag">tag this is a continuation</span>
</div>
我的期望是:
<div id="sample-div" contenteditable="true">
<span class="tag">tag</span> this is a continuation
</div>
所以,我的问题是为什么文本“这是一个延续”也被附加到 span 元素中?如何实现我期望的目标?
最佳答案
最简单的解决方案是将 span 的 contentEditable
属性设置为 false
:
function addTags() {
var tag = document.createElement("span");
tag.className = "tag"
tag.innerHTML = "tag";
tag.contentEditable = false;
$('#sample-div').append(tag);
}
旁注:由于您使用的是 jQuery,因此无需手动创建标签:
function addTags() {
var tag = '<span class="tag" contenteditable="false">tag</span>'
$('#sample-div').append(tag);
}
关于javascript - 为什么文本会附加到错误的 html 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46010627/