javascript 自定义元素类:this.getAttribute('data-*')返回null

jxct1oxe  于 2023-06-04  发布在  Java
关注(0)|答案(2)|浏览(934)

我将Mozzila示例www.example.com中的代码复制并粘贴https://developer.mozilla.org/en-US/docs/Web/Web_Components/Custom_Elements#Observed_attributes到我计算机上的文件中,当我运行它时,每次调用this.getAttribute时都得到null。我看到它在上面的链接上工作,但是当我运行我复制的项目时,它是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);
w1e3prcc

w1e3prcc1#

您应该在connectedCallback()方法中使用this.getAttribute(),因为在调用constructor()方法时可能尚未定义属性。
document.createElement("x-product")
这里的情况是,当<x-product>的属性还没有附加时,只要解析了<x-product>,就调用constructor()

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

查看this question了解更多详细信息。

3bygqnnd

3bygqnnd2#

我还遇到了这样的问题,当从构造函数中调用getAttribute时,getAttribute返回null。我注意到在示例索引文件中,标记具有defer属性。一旦我将defer属性添加到我的script标记中,构造函数中的getAttribute调用就开始工作了。

相关问题