网站搜索标签页查询异常:仅保留最后选中标签结果求助
Let's break down the issue first: every time you switch a model tab, your code is appending the new model keyword to the existing search query instead of replacing the old one. That's why you end up with URLs like search?q=model1%20model2%20selection5 instead of just the latest selected model.
Root Cause
Looking at your loop modifying the product links:
$('.homePageProducts a').each(function(){ var newurl = $(this).attr('href').replace('/search?q=','/search?q='+searchBran+'%20'); $(this).attr('href', newurl); });
This code takes the original href (which might already have a model keyword from a previous tab click) and adds another model to it. Over multiple clicks, this stacks up all the model names. Also, note the typo searchBran instead of searchBrand—it doesn't break functionality here, but fixing it will clean up your code.
Solution
We need to strip out any existing model keywords before adding the new selected one. Here's the fixed code block:
$('.homePageProducts a').each(function(){ var originalHref = $(this).attr('href'); // Remove any previously added model keywords (model1-model5) from the query var cleanedQuery = originalHref.replace(/(model1|model2|model3|model4|model5)%20/g, ''); // Add the currently selected model if exists if (searchBrand) { cleanedQuery = cleanedQuery.replace('/search?q=', '/search?q=' + searchBrand + '%20'); } $(this).attr('href', cleanedQuery); });
Alternative Robust Approach
If you prefer a more maintainable method, parse the URL parameters directly instead of using string replacements:
$('.homePageProducts a').each(function(){ var url = new URL($(this).attr('href'), window.location.origin); var searchQuery = url.searchParams.get('q'); // Strip out any existing model terms searchQuery = searchQuery.replace(/(model1|model2|model3|model4|model5)\s?/g, '').trim(); // Add the new selected model to the front of the query if (searchBrand) { searchQuery = `${searchBrand} ${searchQuery}`; } url.searchParams.set('q', searchQuery); $(this).attr('href', url.toString()); });
Why This Works
Both methods first remove any old model keywords from the search query, then add only the last selected model (from searchBrand) alongside the original search terms. This ensures your URL always reflects just the active tab's model, no matter how many times you switch tabs.
内容的提问来源于stack exchange,提问作者JanBal

