![](/img/trans.png)
[英]How to navigate to another page without reloading the whole page in NextJs?
[英]Javascript: How to navigate on the same page (anchor) without reloading itself
我有一個大頁面,其中包含 6000 多個錨點,例如id="#0000001"
。 為了導航,我添加了一個小的搜索表單,固定在右上角並使用 JS 在文檔上切換位置。 每次搜索后,漏洞頁面將重新加載(大約 4.5MB)。 我想在不重新加載的情況下向上和向下導航/滾動。 與單擊簡單但很長的鏈接列表相同。
它還必須脫機工作,因此 HTML、CSS 和 JS 必須在同一個文檔中。
解決方案代碼(7.5.2020)感謝大家,它適用於此代碼。 我也將<form>
更改為<div>
使用形式:
<div id="suchForm" class="hide_on_print">
<input id="eingabeNr" name="suchFeld" type="text" size="10" value="">
<button type="button" class="strongSuche" id="strongSucheID">🔎</button>
</div>
孔JS(通過按鍵搜索開始-'ENTER'或單擊按鈕:
<script>
window.addEventListener("load", function() {
// press "Enter" in the search field starts searching Strong
document.getElementById("eingabeNr").addEventListener('keypress', (e) => {
if(e.keyCode == 13){
//alert("You pressed \'Enter\'-Key.");
geheZuStrong();
}
});
// "Click" Button starts Strong search
document.getElementById('strongSucheID').addEventListener('click', (e) => {
e.preventDefault();
//alert("You pressed search button"".);
geheZuStrong();
});
// "creates" an ancor and move to it
function geheZuStrong() {
//alert("function: \'geheZuStrong\' running now");
let gesNr = document.getElementById("eingabeNr").value;
switch(gesNr.length) {
case (1):
window.location.hash = "#000000" + gesNr;
break;
case (2):
window.location.hash = "#00000" + gesNr;
break;
case (3):
window.location.hash = "#0000" + gesNr;
break;
case (4):
window.location.hash = "#000" + gesNr;
break;
default:
// Anweisungsblock alternativ
alert('Strong Nummern sind im Bereich 1 bis 6020. Ihre Eingabe war: ' + strongLänge);
}
}
}, false);
</script>
以及帶有 6020 個條目的長鏈接列表(要替換):
<a href="#0000001">1</a> -
<a href="#0000002">2</a> -
...
<a href="#0006020">6020</a> -
由於form
內的按鈕默認行為是提交表單,因此您可以將按鈕的類型設置為按鈕: <button type="button" class="strongSuche">Go</button>
無需任何額外的腳本來阻止默認設置等。請參閱type
在“屬性”下: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
我認為您首先要防止preventDefault
按鈕單擊/表單提交事件:
document.querySelector('#suchForm').addEventListener('submit', (e) => {
e.preventDefault();
//from there, run your scroll:
let gesNr = document.getElementById("eingabeNr").value;
window.location.hash = "#00" + gesNr;
});
如果您想完全避免頁面刷新的可能性,這可能是另一種解決方案(盡管仍需要一些滾動):
<html>
<body>
<select id="navigation" name="navigation">
<option value="1">Go to Section 1</option>
<option value="2">Go to Section 2</option>
<option value="3">Go to Section 3</option>
....
<option value="6020">6020</option>
</select>
<h1 id="001">Section 1</h1>
<h1 id="002">Section 2</h1>
<h1 id="003">Section 3</h1>
...
<h1 id="006020">Section 6020</h1>
</body>
<script>
document.querySelector('#navigation').addEventListener('change', (e) => {
let gesNr = this.value;
window.location.hash = "#00" + gesNr;
});
</script>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.