如何选择自定义元素的孩子后附加到dom?



我想在单击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。也许shadowRootdocument.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]
})

最新更新