【问题标题】:Custom methods of Web componentsWeb组件的自定义方法
【发布时间】:2016-09-11 18:02:44
【问题描述】:

可以在自定义元素上定义自定义函数吗?

类似:

var proto = Object.create(HTMLElement.prototype);
proto.customMethod = function () { ... };

document.registerElement('custom-el', {
  prototype: proto
});

并在元素上调用方法:

var istance = document.createElement('custom-el');
instance.customMethod();

【问题讨论】:

    标签: javascript html web-component custom-element


    【解决方案1】:

    是的,当然。

    您的示例可以在下面的代码 sn-p 中看到:

    自定义元素 v1 的新答案

    class CE extends HTMLElement {
      customMethod() {
        console.log( 'customMethod called' )
      }
    }
    
    customElements.define( 'custom-el', CE )
    
    var instance = document.createElement( 'custom-el' )
    instance.customMethod()

    自定义元素 v0 的旧答案(已弃用)

    var proto = Object.create(HTMLElement.prototype);
    proto.customMethod = function() {
      console.log('customMethod called')
    };
    
    document.registerElement('custom-el', {
      prototype: proto
    });
    var instance = document.createElement('custom-el');
    instance.customMethod();

    【讨论】:

    • @Mariusz 是的,它适用于自定义元素 v0,但现在它们已被弃用......我更新了代码。
    猜你喜欢
    • 2013-12-09
    • 2020-08-28
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2019-03-18
    • 2021-09-30
    相关资源
    最近更新 更多