首页 > 解决方案 > 为什么当我执行 hasAttribute() 并且元素具有属性时,它返回 false?

问题描述

我正在制作一个创建倒计时的自定义元素程序。我有 2 个正在使用的自定义属性 - “ed”和“cd-type”。

我尝试通过 JavaScript 验证器发送它并修复一些错误。我还尝试在构造函数中声明一个值为“this”的变量。

class SCWCountdown extends HTMLElement {
  constructor() {
    super();
    if (this.hasAttribute("ed")) {
      b = new Date(this.getAttribute("ed")).getTime() + new Date.getTimezoneOffset() * 60000;
    } else {
      b = new Date("2020-01-01T00:00:00Z").getTime() + new Date().getTimezoneOffset() * 60000;
    }
    if (this.hasAttribute("cd-type")) {
      c = this.getAttribute("cd-type");
    } else {
      c = "dt";
    }

上面的代码,对于两个条件,都使用了“else”条件中的函数。我试过做

console.log(this.hasAttribute("cd-type"));
console.log(this.hasAttribute("ed"));

他们都返回错误。这是我的 html 文件中的代码:

<!DOCTYPE html>
<html>
<head>
<!--The script with the custom elements-->
<script src="custom.js"></script>
</head>
<body>
<scw-countdown ed="2040-01-01T00:00:00Z" cd-type="uf"></scw-countdown>

链接到我的完整自定义元素脚本:https ://www.scwc.cf/custom.js

倒计时链接:https ://www.scwc.cf/custom-test.html

标签: javascript

解决方案


你的代码对我有用(除了一些关于 Date: 的语法错误TypeError: Date.getTimezoneOffset is not a constructor)。这是一个最小的例子:

  class SCWCountdown extends HTMLElement {
    constructor() {
      super();
      let c;
      if (this.hasAttribute("cd-type")) {
        c = this.getAttribute("cd-type");
      } else {
        c = "dt";
      }
      
      console.log(c);
    }
  }

  window.customElements.define("scw-countdown", SCWCountdown);
<body>
  <scw-countdown cd-type="uf"></scw-countdown>
</body>

另一件需要注意的事情,如果你把console.logs放在customElements.define调用之前,那么cd-typeanded仍然是未定义的,因为SCWCountdown构造函数还没有被调用。


推荐阅读