You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript两函数冲突求助:showPage与myFunction点击触发异常

Fixing Button Click Conflict Between showPage and 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 .posbutton buttons trigger page switching logic.
  • Your submit button will only run myFunction when clicked, no longer interfering with showPage.
  • The added error check acts as a safety net for any accidental invalid data-page values.

Give these changes a try—your submit button should work as expected without hiding the page anymore!

内容的提问来源于stack exchange,提问作者user14593966

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:01:07