请求修改动态内容匹配逻辑:从URL参数改为URL路径关键词
Got it, let's adjust your code to pull the dynamic keyword from the URL path (like dc-Apples.html) instead of query parameters. Here's the modified version with clear explanations:
Modified Code
<style> .dynamic-content { display:none; } </style> <script src="//code.jquery.com/jquery-1.12.0.min.js"></script> <script type="text/javascript"> // Extract keyword from URL path (e.g., pull "apples" from "dc-Apples.html") function getKeywordFromPath() { // Grab the full URL path const path = window.location.pathname; // Extract the filename from the end of the path (e.g., "dc-Apples.html") const filename = path.split('/').pop(); // Remove the file extension to get "dc-Apples" const nameWithoutExt = filename.replace(/\.[^/.]+$/, ''); // Split the string by hyphens and grab the second segment (the keyword) const parts = nameWithoutExt.split('-'); if (parts.length >= 2) { // Convert to lowercase to match your element IDs consistently return parts[1].toLowerCase(); } // Return null if no valid keyword pattern is found return null; } // Store the extracted keyword in a variable var dynamicContent = getKeywordFromPath(); $(document).ready(function() { // Match keyword to corresponding content if (dynamicContent == 'apples') { $('#apples').show(); } else if (dynamicContent == 'oranges') { $('#oranges').show(); } else if (dynamicContent == 'bananas') { $('#bananas').show(); } else { // Show default content if no valid keyword is detected $('#default-content').show(); } }); </script> <!-- Default Dynamic Section --> <div id="default-content" class="dynamic-content"> This is the default content </div> <!-- Dynamic Section 1 --> <div id="apples" class="dynamic-content"> I like apples </div> <!-- Dynamic Section 2 --> <div id="oranges" class="dynamic-content"> I like oranges </div> <!-- Dynamic Section 3 --> <div id="bananas" class="dynamic-content"> I like bananas </div>
Key Changes Breakdown:
- New
getKeywordFromPath()function: Replaces the old query parameter parser. It targets the filename in your URL, strips the extension, splits by hyphens, and pulls out the keyword segment. - Case insensitivity: Converts the extracted keyword to lowercase, so URLs like
dc-Apples.htmlordc-APPLES.htmlwill both correctly match the#appleselement. - Fallback behavior: If the URL doesn't follow the
dc-Keyword.htmlformat (or no valid keyword exists), it still falls back to showing your default content, just like the original code.
内容的提问来源于stack exchange,提问作者Charlie Carver
相关产品推荐
相关产品推荐

