使用 innerHtml 添加到 <div> 元素会创建一个新行吗?

Adding to a <div> element using innerHtml creates a new line?

我有一个工具,它应该是创建清单的一种简单方法,而且它可以工作,但是当我将它用于带有两个复选框的东西时会发生什么,它会在每个复选框之间创建一个新行,是吗?一种阻止它这样做的方法?我的代码在这里 yes/no

<!DOCTYPE html>
<html>
  <h1>Create a checklist</h1>
  <div>
    <input type="text" placeholder="Text for object" id="txt" />
    <button onclick="addYN()">Add yes/no</button>
  </div>
</html>
<div style="background-color: grey;" id="prv"></div>
<script>
  var pv = document.getElementById("prv");
  var txt = document.getElementById("txt");
  function getVarYn() {
    let tx = txt.value;
    return (
      "<div><p>" +
      tx +
      "</p> <p> yes</p> <input type = 'checkbox'/> <p>no </p> <input type = 'checkbox'/> </div> "
    );
  }
  function addYN() {
    var t = txt.value;
    pv.innerHTML = pv.innerHTML + getVarYn();
  }
</script>

问题不在于您创建的 <div>,而是所有 <p> 标签。 <p> 标签是段落,它们确实创建了“一个新的 block/line”

看看这样你就没有换行了

  var pv = document.getElementById("prv");
  var txt = document.getElementById("txt");
  function getVarYn() {
    let tx = txt.value;
    return (
      "<div>" +
      tx +
      "&nbsp;yes<input type = 'checkbox'/>no<input type = 'checkbox'/> </div> "
    );
  }
  function addYN() {
    var t = txt.value;
    pv.innerHTML = pv.innerHTML + getVarYn();
  }
<h1>Create a checklist</h1>
  <div>
    <input type="text" placeholder="Text for object" id="txt" />
    <button onclick="addYN()">Add yes/no</button>
  </div>
<div style="background-color: grey;" id="prv"></div>

注意: 结束 </html> 元素应该始终是 HTML 文档的最后一个元素。其他所有内容都应该在您没有的 <body> 元素内。基本结构是这样的

<!DOCTYPE html>
<html>
  <body>

    <!-- ADD all your HTML content here -->
    <h1>My First Heading</h1>
    <p>My first paragraph.</p>
    

    <!-- BUT NOW you need to finish with all the HTML here -->
    <!-- THE VERY LAST thing here before the closing </body> -->
    <!-- should be the <script> tags -->
  </body>
</html>