【问题标题】:Uncaught ReferenceError: deleted1 is not defined at HTMLButtonElement.onclick未捕获的 ReferenceError:deleted1 未在 HTMLButtonElement.onclick 中定义
【发布时间】:2021-11-01 08:26:10
【问题描述】:

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

Uncaught ReferenceError: deleted1 is not defined at 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>

【问题讨论】:

  • 函数deleted1在哪里定义的?
  • 顺便说一句,label 元素应该与 input 元素相关联 - 通过使用 for="&lt;ID&gt;" 其中 &lt;ID&gt; 是输入元素的 id 或通过将输入封装在 open/ 中结束标签
  • deleted1 在 javascript 中,在 row.innerHTML 的底行
  • 我可以看到函数 deleted1 是用 HTML 字符串编写的——我的问题是它在哪里定义?我在这里看不到该功能,也不知道它的作用。
  • 顺便提一下onclick="'+savePlant()+'"&gt; 是不正确的。在添加该函数/事件处理程序之前,您不需要从 HTML 中转义 - 只需 onclick="savePlant()"&gt; 或更好地使用外部事件侦听器,使用 element.addEventListener('click',savePlant)

标签: javascript html firebase google-cloud-firestore


【解决方案1】:

对于没有使用 Firebase 经验的这种情况,我不知道这是否真的正确,但 deleted1 函数应该只声明一次,并在运行时传入新值。由于似乎依赖于函数体内的变量doc,并且在querySnapshot.forEach((doc) =&gt; { 构造中声明了该变量,因此将其提供给函数的一种方法是作为参数-名称不依赖于传入的实际变量,所以我称之为obj。您最初拥有的 inline 事件处理程序可能会被替换为在将所有 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 )
        };
    })

【讨论】:

  • 非常感谢!这真的很管用,对我有很大帮助
猜你喜欢
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
  • 2020-07-07
  • 2017-05-22
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多