gpt4 book ai didi

javascript - 字符串中 HTML 的替代品

转载 作者:行者123 更新时间:2023-11-30 09:39:49 24 4
gpt4 key购买 nike

我现在正在使用这段代码,但我不太喜欢它的外观。

function createPageSettingsPopup(page) {
return '<div class="form-group">' +
'<label for="page-title">Title</label>' +
'<input type="text" class="form-control" id="page-title" value="' + page.title + '">' +
'</div>'
}

是否有任何替代方法可以将 HTML 写入字符串中以使其看起来更好?

最佳答案

您可以使用模板引擎。这是以牺牲页面中的元素为代价的,但代码看起来更清晰,模板更容易理解为 HTML。将模板放在 type 设置为 text/template 的脚本标签中

<script type="text/template" id="tmpl">
<div class="form-group">
<label for="page-title">Title</label>
<input type="text" class="form-control" id="page-title" value="{{pageTitle}}">
</div>
</script>

然后按如下方式修改您的函数。记得缓存模板。

var template = document.getElementById('tmpl').innerHTML; // cache the HTML
function createPageSettingsPopup(page) {
// Find an replace the {{pageTitle}} with page.title, and then return the HTML string.
return template.replace(new RegExp('{{pageTitle}}', 'gi'), page.title)
}

var template = document.getElementById('tmpl').innerHTML; // cache the HTML
function createPageSettingsPopup(page) {
// Find an replace the {{pageTitle}} with page.title, and then return the HTML string.
return template.replace(new RegExp('{{pageTitle}}', 'gi'), page.title)
}

console.log(
createPageSettingsPopup({title:'Hello World'})
);
<script type="text/template" id="tmpl">
<div class="form-group">
<label for="page-title">Title</label>
<input type="text" class="form-control" id="page-title" value="{{pageTitle}}">
</div>
</script>

上面是模板引擎的一个最小例子,但也有像mustache这样的好例子。 , handlebars.js , 和 pug.js

关于javascript - 字符串中 HTML 的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41691637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com