【问题标题】:Adding to a <div> element using innerHtml creates a new line?使用 innerHtml 添加到 <div> 元素会创建一个新行?
【发布时间】:2021-02-01 20:32:11
【问题描述】:

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

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

【问题讨论】:

    标签: javascript html innerhtml


    【解决方案1】:

    问题不在于您创建的&lt;div&gt;,而是所有&lt;p&gt; 标签。 &lt;p&gt; 标签是段落,它们确实创建了“新块/行”

    这样你就不会有新行了

      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>

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      • 2021-12-08
      • 2018-08-24
      相关资源
      最近更新 更多