JavaScript两函数冲突求助:showPage与myFunction点击触发异常
Hey there! You nailed the root cause—your showPage function is being attached to all buttons on the page, including your submit button. Since the submit button doesn’t have a data-page attribute, clicking it passes undefined to showPage. This leads to document.querySelector('#undefined') returning null, and trying to access style on null throws that TypeError. Plus, the unintended showPage call hides all your table bodies, making the page disappear.
Here’s how to fix this:
Step 1: Restrict showPage to Only Page-Toggling Buttons
Instead of adding the click handler to every button, target only the buttons meant for switching pages—your .posbutton class buttons.
Modify your DOMContentLoaded listener like this:
document.addEventListener('DOMContentLoaded', function() { // Only select buttons with the "posbutton" class document.querySelectorAll('button.posbutton').forEach(button => { button.onclick = function() { showPage(this.dataset.page); } }); });
This way, your submit button (which doesn’t have the posbutton class) won’t trigger showPage when clicked.
Step 2: Add Robust Error Handling (Optional but Smart)
To make showPage more resilient, add a check to ensure the target <tbody> exists before modifying its style. This prevents crashes even if a button has an invalid data-page value:
function showPage(page) { // Hide all tbody elements first document.querySelectorAll('tbody').forEach(tbody => { tbody.style.display = 'none'; }); // Find the target page element const targetPage = document.querySelector(`#${page}`); // Only show it if it exists if (targetPage) { targetPage.style.display = 'table-row-group'; } else { console.warn(`Could not find tbody with ID: ${page}`); } }
Why This Works
- Now only your
.posbuttonbuttons trigger page switching logic. - Your submit button will only run
myFunctionwhen clicked, no longer interfering withshowPage. - The added error check acts as a safety net for any accidental invalid
data-pagevalues.
Give these changes a try—your submit button should work as expected without hiding the page anymore!
内容的提问来源于stack exchange,提问作者user14593966

