Mar*_*ia 5 html javascript events shadow-dom
我试图使用 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 => console.log('badums tss'))
}
}
window.customElements.define('user-name', Quiz)
Run Code Online (Sandbox Code Playgroud)
app.js代码:
import { Quiz } from './quiz.js'
var x = new Quiz()
x.getUserName()
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
小智 2
问题很简单。您的代码实际上创建了两个<user-name>s。
一种是在html中静态创建的:
<user-name></user-name>
Run Code Online (Sandbox Code Playgroud)
另一个是由javascript动态创建的:
var x = new Quiz()
Run Code Online (Sandbox Code Playgroud)
动态文档永远不会附加到文档中,因此您只能在页面上看到静态文档。由于您只调用getUserName()动态监听器,因此click和input监听器永远不会添加到静态监听器中。这就是为什么你没有得到任何回应。
我建议你放入addEventListener()构造函数,然后静态的应该可以正常运行。