如何在 JavaScript 的自定义元素中获取 HTML 元素的 id?

问题描述

我的自定义元素如下所示:

class item extends HTMLElement {
  constructor() {
    super()

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

    const button = document.createElement('button');
    button.setAttribute('id','btn')
    button.textContent = "click here";

    shadow.appendChild(button);
}

我正在尝试创建一个 DOM 事件侦听器来检测另一个 JS 文件中的按钮点击,到目前为止我的代码如下所示:

document.querySelector("item").root.querySelector('#cart').addEventListener("click",function({...});

我被困在 document.querySelector 区域听自定义元素“item”中的按钮点击

这就是我声明它的方式,我基本上是将自定义元素附加到 ul 元素:

HTML 片段:

<ul class="flex-container" id="list"></ul>

JS 代码段:

window.onload = function() {
    console.log("ON LOAD");

    product = document.createElement('item');

    let fcontain = document.getElementById("list");

    fcontain.appendChild(product);

};

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)