我想在单击transaction-add__button
时获得transaction-name__inputbox
值。当按钮被点击时,transactionAddHandler
被调用。
当我尝试使用document.querySelector()
获得该元素时,我得到null。我找不到如何获得输入框的值。
const template = document.createElement("template");
template.innerHTML = `
<link rel="stylesheet" href="/style/transactionAddPanel.css">
<div id="transaction-add-panel">
<div id="transaction-name">
<label for="transaction-name">Transaction Name</label>
<input type="text" placeholder="Required more then 4 characters" id="transaction-name__inputbox">
</div>
<div id="transaction-price">
<label for="transaction-price">Transaction Price</label>
<input type="number" placeholder="Rs.10" id="transaction-price__inputbox">
</div>
<div id="transaction-add">
<button id="transaction-add__button">Add</button>
</div>
</div>
`;
export default class TransactionAddPanel extends HTMLElement {
private readonly transactionAddButton: HTMLButtonElement;
constructor() {
super();
let shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.content.cloneNode(true));
this.transactionAddButton = <HTMLButtonElement>shadowRoot.querySelector("#transaction-add__button");
};
connectedCallback() { this.transactionAddButton.addEventListener("click", this.transactionAddHandler)
};
disconnectedCallback() {
this.transactionAddButton.removeEventListener("click", () => {
return
});
};
transactionAddHandler() {
console.log("clicked")
console.log(document.querySelector("#transaction-name__inputbox"))
// here i got null
};
};
customElements.define("transaction-add-panel", TransactionAddPanel);
元素必须存在于document.body
中,document.querySelector
才能返回[HTML Element]
。
我怀疑shadowRoot.appendChild
没有将template
附加到document.body
。也许shadowRoot
在document.body
中不存在事件。createElement
不附加元素,它在虚拟DOM中创建它。
template
确实被附加到document.body
,它会工作得很好。
const template = document.createElement("template");
template.innerHTML = `
<div id="transaction-add-panel">
<div id="transaction-name">
<label for="transaction-name">Transaction Name</label>
<input type="text" placeholder="Required more then 4 characters" id="transaction-name__inputbox">
</div>
<div id="transaction-price">
<label for="transaction-price">Transaction Price</label>
<input type="number" placeholder="Rs.10" id="transaction-price__inputbox">
</div>
<div id="transaction-add">
<button id="transaction-add__button">Add</button>
</div>
</div>
`;
// [1]: make sure you got template appended to document.body
document.body.appendChild(template.content.cloneNode(true));
document.querySelector("#transaction-add__button").
addEventListener("click",function transactionAddHandler(){
console.log("clicked")
console.log(document.querySelector("#transaction-name__inputbox"))
// here i got [HTML Element]
})