【问题标题】:How can I get the ID of the clicked document and get the title and use/save it in firestore?如何获取单击文档的 ID 并获取标题并将其使用/保存在 Firestore 中?
【发布时间】:2020-11-22 16:53:55
【问题描述】:
const setupProducts = (data) => {
  
    if (data.length) {
      let html = '';
      data.forEach(doc => {
        const product = doc.data();
        const li = `
          <li>
            <div class="collapsible-header grey lighten-4"> ${product.title} </div>
            <div class="collapsible-header grey lighten-4">  ${doc.id} </div>
            <div class="collapsible-body white"> ${product.content} 
            <a href="" class="secondary-content">
            <a class="btn orange modal-trigger" >Get ID</a>
            </a>
          </li>
        `;
        html += li;
      });
      productList.innerHTML = html
    } else {
      productList.innerHTML = '<h5 class="center-align">Login to view products</h5>';
    }
  };

我的想法是我想通过单击文档来获取 ID,然后单击 db.collection('activeWorks').doc(doc.id or product.id (I don't know what's right...)).set 中的 product.title。我不知道该怎么做,请帮忙

【问题讨论】:

    标签: javascript html firebase google-cloud-firestore onclicklistener


    【解决方案1】:

    也许可以这样做:将每个 &lt;li&gt; 元素的 id 标签设置为 Firestore 中的 doc id,然后附加一个 onclick 事件触发器

      const setupProducts = (data) => {
    
    if (data.length) {
      let html = '';
      productList.innerHTML = ''
      data.forEach(doc => {
        const product = doc.data();
        const li = `
          <li id="${doc.id}">
            <div class="collapsible-header grey lighten-4"> ${product.title} </div>
            <div class="collapsible-header grey lighten-4">  ${doc.id} </div>
            <div class="collapsible-body white"> ${product.content} 
            <a href="" class="secondary-content">
            <a class="btn orange modal-trigger" >Get ID</a>
            </a>
          </li>
        `;
        html += li;
        productList.innerHTML += html
        document.getElementById(doc.id).onclick = () => {
            // do firestore stuff here
            // db.collection('activeWorks').doc(doc.id).set(your_data)
        }
      });
    } else {
      productList.innerHTML = '<h5 class="center-align">Login to view products</h5>';
    }
    };
    

    如果我误解了你的问题,我很抱歉

    【讨论】:

    • 感谢您的帮助,如果我尝试这样做,总是会出现错误:“Uncaught TypeError: document.getElementById(...) is null”
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多