JS技术问题:如何将表单值插入URL生成可点击链接
Fixing Your Combined Region + Model URL Generator
Got it, let's get those two pieces working together! The issue right now is that your region selector and model input are updating separate parts of the URL but not syncing up. We'll fix this by creating a single reusable function that builds the full URL every time either the region or model changes.
Here's the Updated Code
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <select class="paselect" id="foo-list"> <option data-country="Australia" data-iso="AUD" data-cur="A$" data-url="au/" >Australia</option> <option data-country="Austria" data-iso="EUR" data-cur="&euro;" data-url="at/" >Austria</option> <option data-country="Brazil" data-iso="BRL" data-cur="B$" data-url="br/" >Brazil</option> </select> <input name='model' type="text" value="iPhone " > <p> <span class="model"></span><br> <span id='url'></span><br> </p> <script> // Reusable function to build and update the full product URL function updateProductUrl() { // Get the selected region's path from the dropdown const selectedRegionPath = $('#foo-list option:selected').attr('data-url'); // Get and format the model name from the input (handles multiple spaces too) const rawModelName = $('input[name="model"]').val().trim(); const formattedModel = rawModelName.toLowerCase().replace(/\s+/g, '-'); // Build the complete URL let fullUrl = `https://www.apple.com/${selectedRegionPath}shop/buy-iphone/`; // Only add the model part if there's text in the input if (formattedModel) { fullUrl += formattedModel; } // Update both the model display and the clickable link $('.model').text(formattedModel); $('#url').html(`<a href="${fullUrl}" target="_blank" >Apple product site</a>`); } // Trigger the update when the model input changes $('input[name="model"]').keyup(updateProductUrl); // Trigger the update when the region dropdown changes $('#foo-list').change(updateProductUrl); // Run once on page load to set the initial URL and model display $(document).ready(updateProductUrl); </script>
What Changed?
- Single Reusable Function:
updateProductUrl()handles all the logic for getting the region path, formatting the model name, and building the full URL. This way, both inputs use the same logic instead of separate code paths. - Robust Model Formatting: Using
replace(/\s+/g, '-')replaces all spaces (even multiple ones) with hyphens, which is more reliable than replacing just a single space. - Sync'd Updates: Now whenever you type in the model input or switch the region dropdown, the full URL updates automatically.
- Initial Page Load: We call
updateProductUrl()when the page loads so the URL and model display are set right away instead of waiting for user input.
This should give you the combined URL you want—like https://www.apple.com/at/shop/buy-iphone/iphone-se when Austria is selected and "iPhone SE" is typed in the input.
内容的提问来源于stack exchange,提问作者yello
相关产品推荐
相关产品推荐

