【问题标题】:Looking for a better way of inserting html code into Javascript寻找将 html 代码插入 Javascript 的更好方法
【发布时间】:2022-01-17 10:31:48
【问题描述】:

我想使用Javascripthtml 元素插入一个长而大量的HTML 代码。我知道innerHTML 是一个很好的方法,但是使用InnerHTML 插入长html 代码以后很难编辑。

这是一个例子:

function display(){
document.getElementById('result').innerHTML = '<div><form id="form" ><p style="border: 2px solid #a1a1a1;background: #dddddd; width: 300px; border- radius: 25px; height:60px;"><b>Search Engine</b><br /></p> <input style = "margin-bottom:20px"id="search" type="button" value="Search"></input></p>'
}
<div id=result></div>
<button onclick='display()'>Display</button>
我有一个非常庞大的html 代码要插入,我很难编辑。

谁能建议我一种更简单的插入html 代码的方法或更好的解决方案?

感谢您的回复!

【问题讨论】:

  • 把它放在一个单独的文件中。更好的是,使用 React 之类的框架可以更轻松地进行更改和插值。

标签: javascript html innerhtml


【解决方案1】:

您可以使用模板文字,这样您就可以拥有更易读的格式。

document.getElementById('result').innerHTML = `
<div>
  <form id="form">
    <p style="border: 2px solid #a1a1a1;background: #dddddd; width: 300px; border- radius: 25px; height:60px;">
      <b>Search Engine</b>
      <br />
    </p>
    <input style="margin-bottom:20px" id="search" type="button" value="Search"></input>
    </p>
`;

【讨论】:

    猜你喜欢
    • 2020-09-06
    • 1970-01-01
    • 2018-05-03
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2017-06-17
    相关资源
    最近更新 更多