在頁面中除了常規連結,若借助 JavaScript,還有相當多種開啟或跳轉頁面的方式。以下為常見做法的彙整。
1. 使用 window.open,可在指定頁面開啟,也能自訂視窗尺寸:
<a href="javascript:window.open('https://www.google.com', '_self')">open a link 1</a>
2. 使用 document.URL 屬性開啟新頁面(此方式在 Firefox 中可能無效):
<a href="javascript:document.URL = 'https://www.google.com'">open a link 2</a>
3. 使用 location.href 屬性:
<a href="javascript:window.location.href='https://www.google.com'">open a link 3</a>
4. 使用 location.assign 方法,效果與 href 相同:
<a href="javascript:window.location.assign('https://www.google.com')">open a link 4</a>
5. 使用 location.replace 方法,與 assign 不同之處在於:被替換掉的頁面 URL 不會進入 history,因此無法用後退回到原頁面:
<a href="javascript:window.location.replace('https://www.google.com')">open a link 5</a>
6. 普通連結——對搜尋引擎最為友善,能讓被連結頁面被搜尋引擎完整抓取:
<a href="https://www.google.com">open a link 6</a>
以上就是 JavaScript 實現頁面跳轉的常用方式彙整,希望對你有所幫助。