innerHTML显示的内容与预期的不同

时间:2020-06-16 02:41:17

标签: javascript html css dom

<!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。

3 个答案:

答案 0 :(得分:2)

制作HTML元素并为其指定ID时,该ID必须用引号引起来,并且还必须包含至少1个字符没有空格,所以我建议将li元素的 id id=1更改为id="1a"(或其中带有字母的内容),然后将document.getElementById("1a").innerHTML更改为新值(在本例中为“ 1a”)

答案 1 :(得分:0)

如果您希望该行看起来像一个项目符号指向的列表,那么您需要将innerHTML的结果放在一个无序列表中。现在,您将其放在一个段落中。

考虑将<p id="demo"></p>更改为:

<ul>
  <li id="demo"></li>
</ul>

答案 2 :(得分:0)

好的,所以长话短说id = 1或id ='1'不会引起任何问题。 它仍然在抓取HTML并且运行良好。 问题是p标记,当您将某些东西放入P标记时,它开始表现不同,并且(BR)中断标记未显示换行符。我将P更改为Div,现在看起来很好。 我也更改/删除了CSS类 .input-group { 职位:相对 显示:-ms-flexbox; / *显示:flex; 现在您可以看到换行符。

<!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  >
               <p id='editable' draggable="false" style="width:400px; outline: none" >Text</p>
               
            </div>
         </li>
      </ul>
<button onclick="testFunction('editable')">update</button>
      <button onclick="myFunction()">Try it</button>
      <div id="demo"></div>
      <script>
         function myFunction() {
           document.getElementById("demo").innerHTML = document.getElementById(1).innerHTML;
         }
         function testFunction(el1) {
          el= document.getElementById(el1);
           var attr = document.createAttribute('contenteditable');
           attr.value = 'true';
           el.parentNode.firstElementChild.setAttributeNode(attr)
           el.parentNode.firstElementChild.focus()
         }
      </script>
   </body>
</html>