如何使用 JavaScript 变量更改 HTML 值?

How to have HTML value change with JavaScript variable?

我正在使用 JS handlebars 库设计一个简单的 HTML 模板,它看起来像:

我有一个JS文件如下:

import template from './entry.hbs'

let propertyVar = 0;
let html = template({
  property: propertyVar;
});

document.body.innerHTML = html;

车把模板 (.hbs) 文件如下:

<div>{{property}}</div>

我的 index.html 看起来像:

<html>
<head>
</head>

<body>

</body>
</html>

这一切都很好,但是如果我在 JS 代码中更新它的值,我怎么能在 HTML 中更新变量 property。 我想在 javascript 中有一个递增 属性 的循环,我希望这个递增显示在 HTML.

添加到 html 此代码 <h1 id="property"></h1>

在你有递增的循环中 属性 添加这段代码 document.getElementById("property").textContent = propertyVariableName

如果您想更新呈现的数据,您将不得不使用应用到模板的最新数据重新分配 HTML。

/**
 * @param {Element|String} elOrSel - An element or selector
 */
const loadTemplate = (elOrSel) =>
  (el => Handlebars.compile(el.innerHTML))
  (typeof elOrSel === 'string' ? document.querySelector(elOrSel) : elOrSel);

/**
 * @param {Function} template - Handlebars template function
 * @param {Object}   data     - Template data
 * @param {Element}  target   - Target element to render HTML to
 */
const render = (template, data, target) => (target.innerHTML = template(data));

const template = loadTemplate('#entry-template');
const result = document.querySelector('.result');

let propertyVar = 0;
const redraw = () => render(template, { property: propertyVar }, result);

redraw();
setInterval(() => {
  propertyVar++;
  redraw();
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>
<script id="entry-template" type="text/x-handlebars-template">
  <div>{{property}}</div>
</script>
<div class="result"></div>