Custom Element类:this.getAttribute('data-*')返回null

Ama*_*lin 6 javascript shadow-dom custom-element

我已经将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>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

Sup*_*arp 15

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

这是在这里的情况constructor(),一旦<x-product>被解析,当它的属性尚未附加时被调用.


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

请查看此问题以获取更多详细信息.

  • 非常真实!现在我明白了为什么将功能移到connectedCallback()之后现在突然“工作”了,谢谢! (2认同)