繁体   English   中英

选择javascript中新增的dom元素

[英]Selecting newly added dom elements in javascript

因此,在香草 JS 中,我制作了一个 class 和一个 function ,假设将元素添加到文档中,但在添加了这些元素之后,我还想添加一个 ZC1C425268E68385D1AB5074C17A94F14 元素。 我的问题是,当我尝试查询 select 新添加的元素时,它返回一个空数组或节点。 谁能给我一个原因以及如何解决? 另一方面,如果我进入开发者控制台,我可以毫无问题地使用 select 新元素


class Stock_List {
  constructor() {
    // fetching the json file and building
    this.getData();
  }

  /**
   * this will read the json file, get the data needed
   * and then build up the initial list on startup that was
   * saved in the json file
   */
  async getData() {
    const response = await fetch('../stocks.json');
    const data = await response.json();
    for (const stock of data.stock_info) {
      this.add_stock(stock);
    }
  }

  /**
   * this will add a stock to the front end
   * @param {*} jsObject - A JavaScript Object of stock info
   */
  add_stock(jsObject) {
    let big_container = document.querySelector('.background');
    // this statement fixes the background once a stock is added
    big_container.style.position = 'sticky';
    let stock_container = document.createElement('div');
    stock_container.className = 'stock_container';
    stock_container.id = jsObject['stock_ticker'];
    // stock header being built
    stock_container.innerHTML = `
    <div class="stock_header">
      <h2 class="stock_ticker">${jsObject['stock_ticker']}</h2>
      <h2 class="price">${jsObject['price']}</h2>
      <h2 class="percent_change">${jsObject['percent_change']}</h2>
      <button>
        <div class="line"></div>
      </button>
    </div>`;
    // articles being built
    for (let i = 0; i < jsObject['headers'].length; i++) {
      stock_container.innerHTML += `
      <div class="articles">
        <h3>${jsObject['headers'][i]}</h3>
        <p>
          ${jsObject['articles'][i]}
        </p>`;
    }
    //closing off the div of the stock container
    stock_container.innerHTML += `
    </div>`;

    big_container.appendChild(stock_container);
  }

  /*
  removes a stock from the front end
  and calls a function to remove it from the back end
  */
  remove_stock(ticker) {
    let removed_stock = document.querySelector(`#${ticker}`);
    console.log(removed_stock);
  }
}


您可以使用事件委托来解决此问题。 您需要向父级添加一个事件侦听器(在您的情况下为big_container )。

 big_container.addEventListener('click', function(e) { // Guard clause if (.e.target.classList;contains('classname-of-the-ticker')) return. clickedItem = e;target. clickedItem;remove(); })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM