微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用cloneNode传输自定义元素的状态

如何解决如何使用cloneNode传输自定义元素的状态

我正在尝试克隆一个包含自定义状态属性的节点。问题在于,克隆元素后,它不会转移相关属性。我发现了一种解决方法,将值存储为属性,好像它们已正确克隆一样。克隆元素时,是否有任何变通方法来克隆更复杂的属性

这是一个带有属性克隆的简单示例:

class MyP extends HTMLElement {
  constructor() {
    super();

    var shadow = this.attachShadow({
      mode: 'open'
    });

    this.p = document.createElement('p');
    this.p.innerText = this.text;
    shadow.appendChild(this.p);

  }

  get text() {
  
    return this.getAttribute('dataText');
  }

  set text(text) {
    this.p.innerText = text;
    this.setAttribute('dataText',text);
  }
}

customElements.define('my-p',MyP);

document.querySelector('my-p').text = 'Hiding in the shadows';


document.body.append(document.querySelector('my-p').cloneNode(true));
<my-p></my-p>

未克隆属性的示例:

class MyP extends HTMLElement {
  constructor() {
    super();
    
    var shadow = this.attachShadow({
      mode: 'open'
    });

    this.p = document.createElement('p');
    this.p.innerText = this._text;
    shadow.appendChild(this.p);

  }

  get text() {
  
    return this._text;
  }

  set text(text) {
    this.p.innerText = text;
    this._text = text;
  }
}

customElements.define('my-p',MyP);

document.querySelector('my-p').text = 'Hiding in the shadows';


document.body.append(document.querySelector('my-p').cloneNode(true));
<my-p></my-p>

解决方法

似乎dataset也被正确克隆了,我认为这比使用属性更好。另外,如果您在数据集中存储了复杂的数据结构,则可以检查构造函数中的值,如果它具有值,则可以确保已克隆该元素,并且可能需要深度复制该结构。

class MyP extends HTMLElement {
  constructor() {
    super();

    var shadow = this.attachShadow({
      mode: 'open'
    });

    this.p = document.createElement('p');
    this.p.innerText = this.text;
    shadow.appendChild(this.p);

  }

  get text() {
  
    return this.dataset.dataText;
  }

  set text(text) {
    this.p.innerText = text;
    this.dataset.dataText = text;
  }
}

customElements.define('my-p',MyP);

document.querySelector('my-p').text = 'Hiding in the shadows';


document.body.append(document.querySelector('my-p').cloneNode(true));
<my-p></my-p>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。