【问题标题】:Problem when trying to add an element to a page using appendChild in JS. Throws an error: "is null, undefined"尝试在 JS 中使用 appendChild 将元素添加到页面时出现问题。引发错误:“为空,未定义”
【发布时间】:2022-01-08 20:44:50
【问题描述】:

我正在尝试通过 Firebase 授权该站点,一切正常,数据已发送到 Firebase 服务器。 但进一步,在 signIn 函数中,我尝试创建一个 h2-element 并将邮件数据放入其中,用户输入并单击登录按钮(我希望将邮件而不是名称显示在站点上),然后在我用红色箭头突出显示的行上出现错误:“autorizationName is null, undefined”,没有数据发送到html。我不明白为什么,请帮忙,我最近在研究JS来解决这个问题。

如果我将一个 JS 脚本添加到两个 HTML 页面,会发生这种情况吗? 也就是index.html和autorization.html这两个我加了autorization.js 我希望在从一页授权时将其重定向到主页。

  const login = document.querySelector(".form-login")
  login.addEventListener('click', signIn)

function signIn() {
  const email = document.querySelector(".email").value
  const password = document.querySelector(".password").value
//   e.preventDefault()

  signInWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
          // Signed in 
          const user = userCredential.user;                        
          console.log("Email firebase: ",  user.email);           

          const user2 = JSON.parse(JSON.stringify(user.email))

          const autorizationName = document.querySelector(".autorization-name__container");
          const autorizationNameTitle = document.createElement("h2");
          autorizationNameTitle.textContent = user2;
          autorizationNameTitle.classList.add("autorization-name__title");
          

          autorizationName.appendChild(autorizationNameTitle); // Error: autorizationName is null, undefined
          window.location.replace("http://192.168.1.65:5500/")  
                 
      })

      .catch((error) => {
          const errorCode = error.code;
          const errorMessage = error.message;
          alert(errorMessage + ", " + errorCode);
      });
  }

以下是截图:

【问题讨论】:

  • 欢迎堆栈溢出!请带tour了解网站规则以及how to ask一个好问题。
  • 请不要分享您的代码截图:将其粘贴到您的问题中并将其格式化为代码。
  • 好吧,我不知道,第一个问题来了

标签: javascript html firebase


【解决方案1】:

一行

autorizationName.appendChild(autorizationNameTitle);

您收到一条错误消息,指出authorizationName 为空,未定义。所以,从逻辑上讲,我们需要看一下上次修改它的值的地方(这里是它的初始化):

const autorizationName = document.querySelector(".autorization-name__container");

众所周知,如果您对document.querySelector 的调用产生undefined,则选择器不匹配任何元素。因此,错误的原因是在您尝试查找时,您的页面中没有包含authorization-name__container 的class 的元素。因此,您需要修复选择器或找出给定元素的创建时间。

【讨论】:

    【解决方案2】:

    字符串“.authorization-name__container”是 100% 错误,尝试从代码中的位置复制粘贴该类,并仔细检查拼写错误的单词。然后,如果这不起作用,请尝试使用 id 而不是类

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多