javascript - 如何以声明方式创建自定义 HTML 元素?

标签 javascript html web-component

我正在尝试以声明方式创建自定义元素,但遇到了问题。我read so many docs ,但由于 super 新技术和不断变化的技术,它们都显得过时或不足。有谁知道如何解决这个问题?当前上下文(this)没有register,我也无法更新模板。我走在正确的道路上吗?

<my-date><my-date>

  <element name="my-date">
    <template>
      <style>
        div {
          color: red;
        }
      </style>
    </template>
    <script>
      this.register({
        prototype: {
          createdCallback: function() {
            this.innerHTML = new Date();
          }
        }
      });
    </script>

http://jsbin.com/oGUKeyU/3/

最佳答案

您尝试使用 lifecycle HTMLElement API :

var proto = Object.create(HTMLElement.prototype);

proto.createdCallback = function() {...};
proto.attachedCallback = function() {...};

var XFoo = document.registerElement('x-foo', {prototype: proto});

在你的情况下,它会是这样的:

var proto = Object.create(HTMLElement.prototype);

proto.createdCallback = function () {
    this.innerHTML = (new Date()).toString()
};

var xMyDate = document.registerElement('x-my-date', {
    prototype: proto
});
var newDateElement = new xMyDate();

alert(newDateElement.innerHTML);

但这仅适用于金丝雀。

关于javascript - 如何以声明方式创建自定义 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21337760/

相关文章:

javascript - 是否可以模拟 isTrusted=true

javascript - 使用 react-chartjs-2 创建对折线图的引用

javascript - JS - 改变 .top 属性

html - 在orderedlist中给一个空格

jquery - CSS:在一个位置垂直居中:绝对div

javascript - node.js HTTP 服务器、请求和响应超时之间的区别

javascript - 更改所有文档链接颜色 Javascript

javascript - polymer 过滤器表达式的上下文

javascript - AngularJS 2 和网络组件、模拟和 polyfill

javascript - Web 组件 : Dom Exception: This name has already been used