我想通过 JS 创建一些 html,因此我需要在 JS 文件中编写 html,如:
function createHtmlSection() {
return "<li class=\"chapter up-wrapper-btn\">" +
"<div>" +
"<button><i class=\"fa fa-plus\" onclick=\"addSection('up',this)\"></i></button>" +
"<label contenteditable=\"true\">section 1</label>" +
"</div>" +
"</li>";
}
Run Code Online (Sandbox Code Playgroud)
是否有工具或一些快捷方式来创建这种类型的 html 字符串?
我的意思是,在这种情况下,我需要手动输入所有这些 html。与+并添加所需的"标志。
可以转换的东西:
<li class="chapter up-wrapper-btn">
<div>
<button><i class="fa fa-plus" onclick="addSection('up',this)"></i></button>
<label contenteditable="true">section 1</label>
</div>
</li>
Run Code Online (Sandbox Code Playgroud)
到我需要手动输入的第一个字符串
您可以使用模板文字(注意反引号)。文字支持多行,您不需要转义引号(您需要转义反引号)。
`<li class="chapter up-wrapper-btn">
<div>
<button><i class="fa fa-plus" onclick="addSection('up',this)"></i></button>
<label contenteditable="true">section 1</label>
</div>
</li>`
Run Code Online (Sandbox Code Playgroud)
例子:
`<li class="chapter up-wrapper-btn">
<div>
<button><i class="fa fa-plus" onclick="addSection('up',this)"></i></button>
<label contenteditable="true">section 1</label>
</div>
</li>`
Run Code Online (Sandbox Code Playgroud)
function createHtmlSection() {
return `
<li class="chapter up-wrapper-btn">
<div>
<button><i class="fa fa-plus" onclick="addSection('up',this)"></i></button>
<label contenteditable="true">section 1</label>
</div>
</li>
`;
}
document.querySelector('#root')
.innerHTML = createHtmlSection();Run Code Online (Sandbox Code Playgroud)
您还可以将参数传递给函数,并使用表达式插值将它们插入到字符串中:
<ul id="root"></ul>Run Code Online (Sandbox Code Playgroud)
function createHtmlSection(label) {
return `
<li class="chapter up-wrapper-btn">
<div>
<button><i class="fa fa-plus" onclick="addSection('up',this)"></i></button>
<label contenteditable="true">${label}</label>
</div>
</li>
`;
}
document.querySelector('#root')
.innerHTML = createHtmlSection('!!! section !!!');Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2267 次 |
| 最近记录: |