如何为关联JavaScript函数的HTML按钮添加跳转至第二个HTML页面的功能?
Got it! Let's tweak your existing code to add the page redirect functionality when the button is clicked. We’ll keep your original features (updating the text and logging the secret message) while adding the redirect. Here are two common, straightforward approaches:
1. Redirect in the Current Browser Window
This will replace the current page with your second HTML file immediately after running your original code:
Updated JavaScript Function
function onButtonClick() { // Keep your existing functionality document.getElementById('instructionstext').innerHTML = "😱"; console.log("Secret message"); // Add this line to redirect — replace with your actual page path window.location.href = "second-page.html"; }
Note: Replace "second-page.html" with the real file path of your second HTML page. If it’s stored in a subfolder, use a relative path like "pages/second-page.html".
2. Open the Second Page in a New Tab
If you want the second page to pop up in a new browser tab instead, use window.open():
Updated JavaScript Function
function onButtonClick() { // Keep your existing functionality document.getElementById('instructionstext').innerHTML = "😱"; console.log("Secret message"); // Add this line to open in a new tab — replace with your actual page path window.open("second-page.html", "_blank"); }
Note: The "_blank" parameter ensures the page opens in a new tab. Omit it or use "_self" if you want it to open in the current window instead.
Quick Tip
Double-check that your second HTML file is in the right location relative to your first page. A wrong path will lead to a 404 error when you click the button!
内容的提问来源于stack exchange,提问作者wLan

