我正在尝试使用 addEventListener 从 Shadow DOM 获取用户的输入,但我没有收到任何响应,也没有收到任何错误。对元素的引用正常工作,因此 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 => console.log('badums tss'))
}
}
window.customElements.define('user-name', Quiz)
app.js 代码:
import { Quiz } from './quiz.js'
var x = new Quiz()
x.getUserName()
html:
<!doctype html>
<html lang="">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="module" src="js/app.js"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<user-name></user-name>
<script nomodule src="build.js"></script>
</body>
</html>
最佳答案
问题很简单。您的代码实际上创建了两个 <user-name>
s。
一种是在 html 中静态创建的:
<user-name></user-name>
另一个是由javascript动态创建的:
var x = new Quiz()
动态的永远不会附加到文档中,因此您只能在页面上看到静态的。由于您只调用
getUserName()
在动态上,click
和 input
监听器永远不会添加到静态监听器中。这就是为什么你没有得到任何回应。我建议你把
addEventListener()
在构造函数中,那么静态的应该正常运行。
关于javascript - shadow DOM 中的 addEventListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59273699/