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

如何优化jQuery/JS冗余if/else?实现按钮ID与模态框标题匹配

Clean Up Redundant If/Else for Modal Titles (jQuery/Native JS Solutions)

Awesome question—those sprawling if/else chains are not only messy but a nightmare to maintain when you add new buttons later. Let's replace that with two clean, scalable approaches that handle both single-word and multi-word button IDs perfectly, no hardcoded conditions needed.


Approach 1: Title Mapping Object (Best for Custom/Non-Patterned Titles)

If some of your button IDs need custom titles (like tabbtn → "Tabs Code" instead of "Tabbtn Code"), a lookup object is the way to go. It keeps all your title logic in one place, making updates trivial.

Step 1: Define Your Title Map

Add this outside your click handler (so it only runs once):

// Map button IDs to their desired modal titles
const titleMap = {
  primarybutton: "Primary Button Code",
  secondarybutton: "Secondary Button Code",
  tertiarybutton: "Tertiary Button Code",
  segmentedcontrols: "Segmented Controls Code",
  "time-picker": "Time Picker Code",
  textfield: "Text Field Code",
  radiobuttons: "Radio Button Code",
  textlink: "Text Link Code",
  tabbtn: "Tabs Code"
};

Step 2: Replace the If/Else Chain

Swap all those conditional checks with a simple lookup:

$(".codeBtn").click(function() {
  const btnId = $(this).attr("id");
  const htmlUrl = "./modals/" + btnId + ".html";
  const jsUrl = "./modals/" + btnId + ".js";
  const cssUrl = "./modals/" + btnId + ".css";

  // Get custom title from map, or fall back to ID + " Code"
  const modalTitle = titleMap[btnId] || `${btnId.charAt(0).toUpperCase() + btnId.slice(1)} Code`;
  $("#modalTitle").html(modalTitle);

  // Keep your existing AJAX calls here
  $.ajax({ url : htmlUrl, dataType: "text", success : function (data) { $(".htmlCode").text(data); } });
  $.ajax({ url : jsUrl, dataType: "text", success : function (data) { $(".jsCode").text(data); } });
  $.ajax({ url : cssUrl, dataType: "text", success : function (data) { $(".cssCode").text(data); } });
});

Approach 2: Auto-Format IDs to Titles (Best for Patterned IDs)

If most of your IDs follow a consistent pattern (like kebab-case time-picker or camelCase primaryButton), you can write a helper function to convert them to proper title case automatically. This eliminates the need to update a mapping object every time you add a new button.

Step 1: Create the Formatting Helper

function formatIdToTitle(id) {
  // Handle kebab-case (split on hyphens)
  let words = id.split("-");
  
  // Handle camelCase (split between lowercase and uppercase letters)
  if (words.length === 1) {
    words = id.replace(/([a-z])([A-Z])/g, "$1 $2").split(" ");
  }
  
  // Capitalize each word and join back together
  const titleCase = words.map(word => 
    word.charAt(0).toUpperCase() + word.slice(1)
  ).join(" ");
  
  return `${titleCase} Code`;
}

Step 2: Combine with Mapping for Exceptions

Use the helper function as a fallback for IDs that don't need custom titles:

$(".codeBtn").click(function() {
  const btnId = $(this).attr("id");
  const htmlUrl = "./modals/" + btnId + ".html";
  const jsUrl = "./modals/" + btnId + ".js";
  const cssUrl = "./modals/" + btnId + ".css";

  // Use custom title if exists, else auto-format
  const modalTitle = titleMap[btnId] || formatIdToTitle(btnId);
  $("#modalTitle").html(modalTitle);

  // Keep your existing AJAX calls here
  $.ajax({ url : htmlUrl, dataType: "text", success : function (data) { $(".htmlCode").text(data); } });
  $.ajax({ url : jsUrl, dataType: "text", success : function (data) { $(".jsCode").text(data); } });
  $.ajax({ url : cssUrl, dataType: "text", success : function (data) { $(".cssCode").text(data); } });
});

Note: This auto-formatting works great for kebab-case or camelCase IDs. For concatenated lowercase IDs without separators (like primarybutton), you’ll still need the mapping object—there’s no way to automatically guess word boundaries!


Why This Is Better

  • Maintainable: Add new buttons by just updating the title map (or nothing, if using auto-formatting).
  • Scalable: No more copying/pasting if/else blocks for every new component.
  • Less Error-Prone: Eliminates typos and missed conditions in long conditional chains.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:32:30