小编Mar*_*ia 的帖子

影子 DOM 中的 addEventListener

我试图使用 Shadow DOM 获取用户的输入addEventListener(),但没有得到任何响应,任何错误。对元素的引用工作正常,因此console.log(input)打印出正确的元素。

(相同的代码在没有 Shadow DOM 的情况下工作得很好,但我必须将它包含在我的项目中。)

这是我的代码(当然这些事件只是为了检查):

const template = document.createElement('template')
template.innerHTML = /* html */`
<div id="username">
  <p>Please choose your username!</p>
  <input id="username_input" type="text" placeholder="enter username">
  <button>Ok</button>
</div>
`
/**
 * @class Quiz
 * @extends {window.HTMLElement}
 */
export class Quiz extends window.HTMLElement {
  constructor () {
    super()
    this.attachShadow({ mode: 'open' })
    this.shadowRoot.appendChild(template.content.cloneNode(true))
  }

  getUserName () {
    const button = this.shadowRoot.querySelector('button')
    const inputUname = this.shadowRoot.querySelector('#username input')
    console.log(button)
    button.addEventListener('click', event => console.log('badum tss'))
    inputUname.addEventListener('input', event …
Run Code Online (Sandbox Code Playgroud)

html javascript events shadow-dom

5
推荐指数
1
解决办法
2135
查看次数

标签 统计

events ×1

html ×1

javascript ×1

shadow-dom ×1