简体   繁体   English

jQuery 函数在 Promise.then() 中不可用

[英]jQuery function is not available in Promise.then()

I am implementing a threaded comment board on my website with this jQuery library .我在我的网站上使用这个 jQuery 库实现了一个线程评论板。

Here is a part of my index.html where comment data are downloaded from Firebase and displayed in the front end through the library.这是我的index.html的一部分,其中评论数据是从 Firebase 下载的,并通过库显示在前端。

For an experiment, I tried to display a comment board in an element (eg body ).作为实验,我尝试在一个元素(例如body )中显示一个评论板。 In the first code below, it does not throw any error.在下面的第一个代码中,它不会抛出任何错误。 However, this is not the right place to call the comment board function because the function has to use the data from Firebase.但是,这不是调用评论板函数的正确位置,因为该函数必须使用来自 Firebase 的数据。

So, I moved the jQuery function to the then method of db.collection (second code) so that the comment function can all the data from Firebase (stored in querySnapshot ).因此,我将 jQuery 函数移至db.collectionthen方法(第二个代码),以便评论函数可以获取来自 Firebase 的所有数据(存储在querySnapshot中)。

Then the second one throws the error然后第二个抛出错误

Uncaught (in promise) TypeError: $(...).comments is not a function未捕获(承诺)TypeError: $(...).comments is not a function

Why is this happening?为什么会这样? How can the jQuery function correctly use the data from Firebase? jQuery 函数如何正确使用来自 Firebase 的数据?


First code第一个代码

<script>
window.onload = () => {
  $("body").comments({
    profilePictureURL: 'sample-icon.png',
    getComments: (success, error) => {
      var commentsArray = [{
          ...
      }];
      success(commentsArray);
    }
  });
  const db = firebase.firestore()
  db.collection("projects").get().then(querySnapshot => {
   ...
  })
}
</script>

Second code第二码

<script>
window.onload = () => {
  const db = firebase.firestore()
  db.collection("projects").get().then(querySnapshot => {
    $("body").comments({
      profilePictureURL: 'sample-icon.png',
      getComments: (success, error) => {
        var commentsArray = [{
          ...
        }];
        success(commentsArray);
      }
    });
  })
}
</script>

Here is a part of the file structure of my website这是我网站文件结构的一部分

/public        <--- Hosting on Firebase
  index.html
  /forum
    index.html <--- the index.html shown in the question above
  /css
    jquery-comment.css <--- from the jQuery library
  /js
    jquery-comment.js <---  from the jQuery library

 <script> window.onload = () => { const db = firebase.firestore() // use a closure const jq = $; db.collection("projects").get().then(querySnapshot => { jq("body").comments({ profilePictureURL: 'sample-icon.png', getComments: (success, error) => { var commentsArray = [{... }]; success(commentsArray); } }); }) } </script>

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

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