首页 > 解决方案 > 单击 amp 网页时动态添加 html

问题描述

使用 AMP 时是否可以在点击时将 HTML 动态添加到网页?

类似的东西

<button on="tap:AMP.setState({foo: 'amp-bind'})">Say "Hello amp- 
bind"</button>

<div [text]="foo">This is the placeholder to append the new 
content</div>

而不是文本HTML?

标签: amp-html

解决方案


您需要的可以使用 amp-script 来实现。

https://github.com/ampproject/amphtml/blob/master/extensions/amp-script/amp-script.md

来自 github:

<!-- hello-world.html -->
<amp-script layout="container" src="https://example.com/hello-world.js">
  <button id="hello">Insert Hello World!</button>
</amp-script>


// hello-world.js
const button = document.getElementById('hello');
button.addEventListener('click', () => {
  const el = document.createElement('h1');
  el.textContent = 'Hello World!';
  // `document.body` is effectively the <amp-script> element.
  document.body.appendChild(el);
});

推荐阅读