javascript - 为什么当我执行 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
解决方案
你的代码对我有用(除了一些关于 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.log
s放在customElements.define
调用之前,那么cd-type
anded
仍然是未定义的,因为SCWCountdown
构造函数还没有被调用。
推荐阅读
- entity-framework - 通过 EF Core EnsureCreated 创建数据库时如何设置 Azure Sql 服务层?
- android - 如何在android studio中植入admob
- php - CakePHP 3.8.6:添加新内容时授权失败
- scheme - 简化派生表达式方案
- python-3.6 - 主管有日志中断
- node.js - 在 nodejs 中上传和读取文件,无需任何第三方模块,如 multer、express-fileupload、busyboy 等,
- javascript - 测试“非空”并在 JS 中相应设置值的紧凑方法
- amazon-web-services - 克隆 AWS RDS 中的一个数据库以获得测试数据库
- php - 带有 Prestashop 1.7 的 php:致命错误:未捕获的错误:未在中找到类“Db”
- haskell - 删除单词的第一个字母并将其附加到末尾的函数(Haskell)