我正在制作一个自定义元素程序,用于创建倒计时。我有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
答案 0 :(得分:1)
您的代码对我有用(除了有关日期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.log
放在customElements.define
调用之前,则cd-type
和ed
仍将是未定义的,因为SCWCountdown
构造函数尚未被调用。