【问题标题】:Custom Element class: this.getAttribute('data-*') returns null自定义元素类:this.getAttribute('data-*') 返回 null
【发布时间】:2017-07-31 21:19:29
【问题描述】:

我已复制并粘贴到 Mozzila 示例中的代码 https://developer.mozilla.org/en-US/docs/Web/Web_Components/Custom_Elements#Observed_attributes 到我计算机上的文件,当我运行它时,每次调用 this.getAttribute 都会得到 null。 我看到它在上面的链接上工作,但是当我运行我复制的项目时,它是空的,我写的另一个项目中也发生了同样的事情,基于这个例子:

HTML 文件:

If nothing appeared below, then your browser does not support Custom Elements yet.
<x-product data-name="Ruby" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/ruby.png" data-url="http://example.com/1"></x-product>
<x-product data-name="JavaScript" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/javascript.png" data-url="http://example.com/2"></x-product>
<x-product data-name="Python" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/python.png" data-url="http://example.com/3"></x-product>

JS 文件:

// Create a class for the element
class XProduct extends HTMLElement {
  constructor() {
    // Always call super first in constructor
    super();

    // Create a shadow root
    var shadow = this.attachShadow({mode: 'open'});

    // Create a standard img element and set it's attributes.
    var img = document.createElement('img');
    img.alt = this.getAttribute('data-name');
    img.src = this.getAttribute('data-img');
    img.width = '150';
    img.height = '150';
    img.className = 'product-img';

    // Add the image to the shadow root.
    shadow.appendChild(img);

    // Add an event listener to the image.
    img.addEventListener('click', () => {
      window.location = this.getAttribute('data-url');
    });

    // Create a link to the product.
    var link = document.createElement('a');
    link.innerText = this.getAttribute('data-name');
    link.href = this.getAttribute('data-url');
    link.className = 'product-name';

    // Add the link to the shadow root.
    shadow.appendChild(link);
  }
}

// Define the new element
customElements.define('x-product', XProduct);

【问题讨论】:

    标签: javascript shadow-dom custom-element


    【解决方案1】:

    您应该在connectedCallback() 方法中使用this.getAttribute(),因为在调用constructor() 方法时可能尚未定义属性。

    这里的情况是 constructor() 在解析 &lt;x-product&gt; 后立即被调用,此时它的属性尚未附加。


    请注意,如果您将customElement.define() 语句放在 html 代码&lt;x-product data-...&gt; 之后,它仍然可以工作。这是因为当标签被定义为自定义元素时,属性已经附加到 &lt;x-product&gt; 元素。

    查看this question了解更多详情。

    【讨论】:

    • 非常真实!现在我明白为什么在我将功能移动到connectedCallback()之后它现在“突然”工作了,谢谢!
    【解决方案2】:

    我也遇到了从构造函数中调用 getAttribute 时返回 null 的问题。我注意到在示例 index file 中,标签具有 defer 属性。将 defer 属性添加到脚本标记后,构造函数中的 getAttribute 调用就开始工作了。

    【讨论】:

      猜你喜欢
      • 2013-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 2016-03-15
      • 1970-01-01
      相关资源
      最近更新 更多