簡體   English   中英

自定義元素數據屬性不起作用

[英]Custom Elements data attributes not working

我正在嘗試制作一個自定義html元素,並將其實例化傳遞給一些自定義數據標簽。 問題在於它的數據集總是空的,我無法弄清楚自己在做什么錯。 我在下面的例子從MDN定制元素..和這個例子,在我的瀏覽器的工作..此外,我能順利通過自定義數據標簽,當我在我的網頁上添加一個標准的IMG,而不是當我用我的自定義HTML元件。

以下是我的js文件(在MyImage.js中定義)和我的html文件。 旁邊有一個名為small.jpg的圖像。

 class MyImage extends HTMLElement { constructor() { // Always call super first in constructor super(); // Create a dom shadow root var domShadow = this.attachShadow({mode: 'open'}); // Create a standard img element and set its attributes. var img = document.createElement('img'); img.alt = this.dataset.name; img.src = this.dataset.img; // Add the image to the shadow root. domShadow.appendChild(img); } } // Define the new element customElements.define('my-image', MyImage); 
 <html> <head> <title>myimage</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="MyImage.js"></script> </head> <body> <my-image data-name="My special image name" data-img="small.jpg"></my-image> </body> </html> 

更新您的代碼以從DOM實例獲取以下屬性

img.alt = this.getAttribute('data-name');
img.src = this.getAttribute('data-img');

如果我更改腳本的加載位置,則該片段有效。 如果我將script元素放在正文的末尾,則示例可以正常工作。 請參見下面的代碼段:

 // Create a class for the element class MyImage extends HTMLElement { constructor() { // Always call super first in constructor super(); // Create a dom shadow root var domShadow = this.attachShadow({mode: 'open'}); // Create a standard img element and set its attributes. var img = document.createElement('img'); img.alt = this.dataset.name; img.src = this.dataset.img; // Add the image to the shadow root. domShadow.appendChild(img); } } // Define the new element customElements.define('my-image', MyImage); 
 <html> <head> <title>myimage</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <my-image data-name="My special image name" data-img="small.jpg"></my-image> <script src="MyImage.js"></script> </body> </html> 

所以現在我的問題變成了:為什么? 我知道腳本聲明/引用的位置會在頁面中加載時受到影響,但是沒有人確切知道這里發生的事情導致實例化我的自定義元素時無法正確傳遞自定義屬性嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM