【发布时间】:2020-10-05 13:36:45
【问题描述】:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<ul>
<li id=1 class="draggable" draggable="true">
<div class="input-group" >
<p draggable="false" style="width:400px; outline: none" >Text</p>
<button onclick="testFunction(this)">update</button>
</div>
</li>
</ul>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = document.getElementById(1).innerHTML;
}
function testFunction(el) {
var attr = document.createAttribute('contenteditable');
attr.value = 'true';
el.parentNode.firstElementChild.setAttributeNode(attr)
el.parentNode.firstElementChild.focus()
}
</script>
</body>
</html>
当按下“更新”按钮并向段落添加新文本和行并按下“尝试”按钮时,新行就会消失。我希望它是一样的,因为我复制了 innerHTML。
【问题讨论】:
-
document.getElementById(1)不是你想要的。 HTML 元素id值是字符串。使用document.getElementById('1'),但您应该始终使用以字母而非数字开头的元素id值。 -
另外,您应该避免使用
.innerHTML,因为它是一项昂贵的操作(因为这意味着文本必须由浏览器解析和处理)。改用parent.appendChild( other.cloneNode() )会快得多(而且更简单,imo),请参阅developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
标签: javascript html css dom