document.location.href跟document.getElementById不起作用。

huangapple go评论134阅读模式
英文:

document.location.href followed by document.getElementById does not work

问题

当我使用document.location.href跳转到另一个HTML页面,然后尝试修改新页面中的元素(我会使用getElementById),我发现网页中找不到该元素。我认为这是因为新页面尚未完全加载,它正在查找先前的HTML页面... 有什么办法可以解决这个问题吗?
例如:

async function navigateToAccount(accId, userStatus, userBalance) {
  // 获取账户信息
  try {
    const token = localStorage.getItem('token');
    const response = await fetch(
      'someapi/api/getAccountDetails/' + accId,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
      }
    );
    const data = await response.json();
    if (data.status == false) {
      throw new Error(data.message);
    }
    window.location.href = 'accountPage.html';
    // 下面的代码不会执行
    const accountName = document.getElementById('accountPageName');
    accountName.textContent = localStorage.getItem('name');
    const accountBalance = document.getElementById('accountPageBalance');
    accountBalance.textContent = userBalance;
    const ccNumber = document.getElementById('accountPageccNumber');
    ccNumber.textContent = data.account.creditCard.number;
    const ccName = document.getElementById('accountPageccName');
    ccName.textContent = localStorage.getItem('name');
    const ccExp = document.getElementById('accountPageccExp');
    ccExp.textContent = data.account.creditCard.expiryDate;
    const ccCvv = document.getElementById('accountPagecccvv');
    ccCvv.textContent = data.account.creditCard.cvv;
  } catch (err) {
    console.log(err.message);
  }
}

我会收到一个错误,说找不到具有ID“accountPageName”的元素。

英文:

When i do a document.location.href to go to another HTML page and then try to modify elements in the new page (which I would use getElementById for), I get that the element is not found in the webpage. I think it is because the new page is not fully loaded yet and it is looking in the previous HTML page.. Any idea how I can fix this issue?
For example:

async function navigateToAccount(accId, userStatus, userBalance) {
  //fetch account information
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(
      'someapi/api/getAccountDetails/' + accId,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
      }
    )
    const data = await response.json()
    if (data.status == false) {
      throw new Error(data.message)
    }
    window.location.href = 'accountPage.html'
//the below is not executing
    const accountName = document.getElementById('accountPageName')
    accountName.textContent = localStorage.getItem('name')
    const accountBalance = document.getElementById('accountPageBalance')
    accountBalance.textContent = userBalance
    const ccNumber = document.getElementById('accountPageccNumber')
    ccNumber.textContent = data.account.creditCard.number
    const ccName = document.getElementById('accountPageccName')
    ccName.textContent = localStorage.getItem('name')
    const ccExp = document.getElementById('accountPageccExp')
    ccExp.textContent = data.account.creditCard.expiryDate
    const ccCvv = document.getElementById('accountPagecccvv')
    ccCvv.textContent = data.account.creditCard.cvv
  } catch (err) {
    console.log(err.message)
  }
}

I would get an error saying that element with Id accountPageName is not found.

答案1

得分: 0

第一,您可以从当前页面请求数据,然后调用新页面并将数据传递给它。这就是您本来会用您的代码做的事情,但是做法是错误的。我认为这样做很繁琐且不必要。 (不好的做法)

第二,您可以打开新页面,如果需要的话将用户ID传递给它 - 尽管我认为它可以查询 - 这是我们在当前页面需要做的一切,因为我们已经将用户重定向到了一个新文件。然后,在新页面上,您可以下载用户数据。 (更好的做法)

(我之所以选择这种方法还有另一个原因。想象一下,如果您想从另一个文件重定向用户到accountPage.html。那么,您是否需要在那里再次编码数据检索?那将是代码重复,而且相当繁琐的任务。相反,您应该将所有属于它的东西直接编码到accountPage.html中。如果下载账户数据对于页面的正确显示是必要的,那么您应该在accountPage.html中执行数据检索。)

home.html

<button onclick="navigateToAccount(123)">前往我的账户</button>
/**
 ** 在加载home.html并单击按钮时运行
 */
function navigateToAccount(accId) {
  window.location.href = `../accountPage.html?accId=${accId}` // 重定向到新的HTML文件,结束当前请求
}

accountPage.html

<div id="accName">加载中...</div>
/**
 ** 在加载accountPage.html时运行
 */

// 从URL中获取参数(http://example.com/accountPage.html?accId=123)
// - 之后可以调用params.accId,返回123
const params = new Proxy(new URLSearchParams(window.location.search), {
  get: (searchParams, prop) => searchParams.get(prop),
})

let accountDetails = null

async function getAccountDetails(accId) {
  const response = await fetch(`http://example.com/api/getAccountDetails/${accId}`) // 等待API响应
  accountDetails = await response.json() // 保存API的响应

  // 调用打印方法
  printAccountDetails()
}

// 打印文本到div中
function printAccountDetails() {
  document.getElementById('accName').innerText = accountDetails?.accName ?? '未知'
}

// 在DOM完全加载后调用获取方法
window.addEventListener("DOMContentLoaded", (event) => {
  getAccountDetails(params.accId)
})

更多信息

使用JavaScript跳转到新的HTML页面 - StackOverflow答案
如何在JavaScript中获取查询字符串的值 - StackOverflow答案
在JavaScript中使用Fetch API - MDN文档

await - 等待过程结束 - MDN文档
async function - 使用await的必要性 - MDN文档

DOMContentLoaded事件 - MDN文档

英文:

You can do two things.

First, you request the data from the current page, then you invoke the new page and pass it the data. This is what you would have done with your code, but incorrectly. I think this is cumbersome and unnecessary. (bad)

Second, you open the new page, pass the user ID to it if necessary - although I think it can be queried - and that's all we need to do on the current page because we redirected the user to a new file. On the new page, you then download the user data. (better)

(I would choose this approach for another reason as well. Just imagine if you want to redirect the user to the accountPage.html from another file. Then, would you have to encode the data retrieval again there? That would be code duplication and quite a cumbersome task. Instead, you should encode everything that belongs to it directly into the accountPage.html. If downloading the account data is necessary for the proper display of the page, then you should perform that data retrieval within the accountPage.html.)

home.html

&lt;button onclick=&quot;navigateToAccount(123)&quot;&gt;Go to My Account&lt;/button&gt;
/**
 ** Will run when loaded home.html and click to button
 */
function navigateToAccount(accId) {
  window.location.href = `../accountPage.html?accId=${accId}` // redirect to new html file and here end current request
}

accountPage.html

&lt;div id=&quot;accName&quot;&gt;Loading...&lt;/div&gt;
/**
 ** Will run when loaded accountPage.html
 */

// Get Params from URL (http://example.com/accountPage.html?accId=123)
// - after it can call params.accId what is return 123
const params = new Proxy(new URLSearchParams(window.location.search), {
  get: (searchParams, prop) =&gt; searchParams.get(prop),
})

let accountDetails = null

async function getAccountDetails(accId) {
  const response = await fetch(`http://example.com/api/getAccountDetails/${accId}`) // wait API response 
  accountDetails = await response.json() // save API answer

  // call print method
  printAccountDetails()
}

// print texts to divs
function printAccountDetails() {
  document.getElementById(&#39;accName&#39;).innerText = accountDetails?.accName ?? &#39;unknown&#39;
}

// Call get method after DOM loaded fully
window.addEventListener(&quot;DOMContentLoaded&quot;, (event) =&gt; {
  getAccountDetails(params.accId)
})

More information

Jumping to a new HTML page with JavaScript - StackOverflow Answer<br>
How can I get query string values in JavaScript - StackOverflow Answer<br>
Using the Fetch API in JavaScript - MDN Docs

await - Wait process end - MDN Docs<br>
async function - What need to await using - MDN Docs

DOMContentLoaded event - MDN Docs

huangapple
  • 本文由 发表于 2023年6月18日 22:16:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76500997.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定