首页 > 解决方案 > 未捕获的 ReferenceError:deleted1 未在 HTMLButtonElement.onclick 中定义

问题描述

嘿,有人能帮帮我吗?我试图删除其中一行,当我已经声明了按钮时出现了下面的错误。

未捕获的 ReferenceError:deleted1 未在 HTMLButtonElement.onclick 中定义

是因为脚本类型是模块吗?有人可以帮帮我吗?

这是我的代码:

HTML

<div class="container-fluid">
        <table class="table table-bordered">
            <thead class="thead-dark">
              <th style="width: 14%;">Email</th>
              <th style="width: 23%;">Address</th>
              <th style="width: 16%;">Brought</th>
              <th style="width: 5%;">Quantity</th>
              <th style="width: 5%;">Status</th>
              <th>Options</th>
            </thead>
            <tbody id="tbody1">
            </tbody>
        </table>
    </div>

    <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true" data-keyboard="false" data-backdrop="static">
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLongTitle">Plant Record</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            </div>
            <div class="modal-body">
                <label class="labs">Email: </label>
                <input type="text" disabled id="CategoryMod"><br>
                <label class="labs">Item Brought: </label>
                <input type="text" disabled id="ImageMod"><br>
                <label class="labs">Quantity: </label>
                <input type="text" disabled id="NameMod"><br>
                <label class="labs">Address: </label>
                <input type="text" disabled id="PriceMod"><br>
                <label class="labs">Address Code: </label>
                <input type="text" disabled id="StockMod"><br>
                <label class="labs">Status: </label>
                <select class="status" id="inputStatus">
                  <option selected>Choose...</option>
                  <option value="1">Prepared</option>
                  <option value="2">Delivered</option>
                </select>
            </div>
            <div class="modal-footer">
            <button id="saveModeBtn" type="button" class="btn btn-success" onclick="'+savePlant()+'">Save Update</button>
            </div>
        </div>
        </div>
    </div>

Javascript

<script type="module">
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-app.js";
    import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-analytics.js";
    import { getFirestore, doc, setDoc, collection, addDoc, getDocs, onSnapshot, query, where, orderBy, limit } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-firestore.js";
    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries
  
    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
      apiKey: *******,
      authDomain: ******,
      databaseURL: *******",
      projectId: "*******",
      storageBucket: "*******",
      messagingSenderId: "********",
      appId: "*********",
      measurementId: "*****"
    };
  
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
    const firestore = getFirestore();
        
    const querySnapshot = await getDocs(collection(firestore, "ordered"), orderBy("broughtAt"));
            querySnapshot.forEach((doc) => {
                let id = doc.id
                let data = doc.data()

                const list = document.getElementById("tbody1");
                const row = document.createElement("tr");

                row.innerHTML += `               
                    <td class="grid-item">${(data.paidby)}</td>
                    <td class="grid-item">No. ${(data.numbur)}, Simpang ${(data.spg)}, Jalan ${(data.jln)}, ${(data.district)}, ${(data.code)}</td>
                    <td class="grid-item">'${(data.product)}'</td>
                    <td class="grid-item">${(data.amount)}</td>
                    <td class="grid-item">${(data.status)}</td>
                    <td class="grid-item"><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">Update Status</button><button type="button" class="btn btn-danger btn-primary my-2 ml-2" onclick="deleted1('${id}')">Delete</button></td>
                    `;

                    list.appendChild(row);

                    async function deleted1(id){
                        await deleteDoc(doc(firestore, "ordered", id));
                    }
            });
      </script>

标签: javascripthtmlfirebasegoogle-cloud-firestore

解决方案


我不知道这对于没有 Firebase 经验的这种情况是否真的正确,但该deleted1函数应该只声明一次,并在运行时传入新值。由于似乎依赖doc于函数体中的变量,并且在构造中声明了该变量,因此向函数提供该变量的querySnapshot.forEach((doc) => {一种方法是作为参数-名称不依赖于传入的实际变量的名称,因此我叫它objinline在将所有 HTML 附加到文档后,您最初拥有的事件处理程序可能会替换为应用的外部事件侦听器。

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const firestore = getFirestore();


async function deleted1( obj, id ){
    await deleteDoc( obj( firestore, "ordered", id ) );
};
    
const querySnapshot = await getDocs(collection(firestore, "ordered"), orderBy("broughtAt"));
    querySnapshot.forEach((doc) => {
        let id = doc.id;
        let data = doc.data();

        const list = document.getElementById("tbody1");
        const row = document.createElement("tr");

        row.innerHTML += `               
            <td class="grid-item">${(data.paidby)}</td>
            <td class="grid-item">No. ${(data.numbur)}, Simpang ${(data.spg)}, Jalan ${(data.jln)}, ${(data.district)}, ${(data.code)}</td>
            <td class="grid-item">'${(data.product)}'</td>
            <td class="grid-item">${(data.amount)}</td>
            <td class="grid-item">${(data.status)}</td>
            <td class="grid-item">
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">Update Status</button>
                <button type="button" class="btn btn-danger btn-primary my-2 ml-2" data-id="${id}">Delete</button>
            </td>
            `;

            list.appendChild(row);
    });
    
    document.querySelectorAll('td > button.btn').forEach(bttn=>{
        bttn.addEventListener('click',function(e){
            console.log( doc, this.dataset.id )
            deleted1( doc, this.dataset.id )
        };
    })

推荐阅读