Tôi đã một yếu tố xác định tùy chỉnh như sau:Không thể xây dựng lỗi 'CustomElement' khi tập tin JavaScript được đặt trong đầu
class SquareLetter extends HTMLElement {
constructor() {
super();
this.className = getRandomColor();
}
}
customElements.define("square-letter", SquareLetter);
Khi tệp JavaScript được bao gồm trong HTML <head>
thẻ, giao diện điều khiển báo cáo Chrome lỗi này :
Uncaught DOMException: Failed to construct 'CustomElement': The result must not have attributes
Nhưng khi tệp JavaScript được đưa vào trước thẻ kết thúc </body>
, mọi thứ đều hoạt động tốt. Lý do là gì?
<head>
<script src="js/SquareLetter.js"></script> <!-- here -->
</head>
<body>
<square-letter>A</square-letter>
<script src="js/SquareLetter.js"></script> <!-- or here -->
</body>
Bản sao có thể có của [Không thể truy cập các thuộc tính của phần tử tùy chỉnh từ hàm tạo của nó] (http://stackoverflow.com/questions/42251094/cannot-access-attributes-of-a-custom-element-from-its-constructor) – Supersharp