【问题标题】:window onload function issue窗口加载功能问题
【发布时间】:2021-10-18 09:04:36
【问题描述】:
window.onload = prepareButton;

function prepareButton() {
  document.getElementById('slist').onclick = function() {
    window.location = "students";
  }
}

一旦我点击一个slist 元素,它恰好是一个像这样结构的<p> 标签

<p type="button" id="slist" class="active">Student List</p>

它使页面永远重新加载,我不知道为什么。

【问题讨论】:

  • 当你说“永远重新加载”时,你的意思是它会一遍又一遍地重新加载吗?或者新页面永远不会加载?
  • 您知道这段代码会用students 替换最后一个URL 段吗?这是你需要做的吗?
  • 此代码中的任何内容都不应导致无限/重复重新加载。如果没有minimal reproducible example,我们将无能为力。
  • 我试图帮助你,但被否决了,所以我删除了它。我希望你能找到解决办法。因为我给的那个对我有用。
  • @James 问题中的代码同样有效。您的回答没有解释为什么改变它会产生任何影响(事实上,它们没有产生任何影响。)正如预期的那样(并由 OP 确认),问题出在其他地方。那些反对票似乎是有道理的。

标签: javascript html


【解决方案1】:

您应该将整个 URL or path 分配给 window.location,而不仅仅是一个词:

window.onload = prepareButton;

function prepareButton() {
  document.getElementById('slist1').onclick = function() {
    window.location = "stackoverflow.com/questions";
  }
  document.getElementById('slist2').onclick = function() {
    window.location = "/questions";
  }
  document.getElementById('slist3').onclick = function() {
    window.location = "../..";
  }
}
All these buttons will take you to the StackOverflow questions overview.
<p type="button" id="slist1">Using the whole URL</p>
<p type="button" id="slist2">Using an absolute path</p>
<p type="button" id="slist3">Using a relative path</p>

(抱歉 - 由于某种原因,它在 StackSnippet 中不起作用……)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多