实现用下拉选项命令替换JavaScript内容并在输入框展示结果的需求
Got it, let's get this working exactly how you want. Here's a complete solution that updates the input with the result of your show function whenever you pick a new option from the dropdown, plus it even updates the JavaScript code to reflect the current selection if that's something you need:
<select id="change"> <option>Cat</option> <option>Dog</option> <option>Fish</option> </select> <script type="text/javascript" id="showScript"> // First, define your show function here - replace this with your actual logic function show(animal) { // Example return value; swap this with whatever your function actually produces return `You selected ${animal} → ${animal === 'Cat' ? 'Meow!' : animal === 'Dog' ? 'Woof!' : 'Blub!'}`; } // Initialize the input with the default Cat selection document.querySelector('input').value = show('Cat'); </script> <input/> <script type="text/javascript"> // Grab references to our elements const dropdown = document.getElementById('change'); const inputBox = document.querySelector('input'); const scriptTag = document.getElementById('showScript'); // This runs whenever the dropdown selection changes dropdown.addEventListener('change', () => { const selectedAnimal = dropdown.value; // Run the show function and put the result in the input const result = show(selectedAnimal); inputBox.value = result; // Optional: Update the JavaScript code in the script tag to match the current selection // This is what addresses your request to "modify JavaScript content" const currentScript = scriptTag.textContent; const updatedScript = currentScript.replace(/show\(['"][^'"]+['"]\);/, `show('${selectedAnimal}');`); scriptTag.textContent = updatedScript; }); </script>
Let me break down what's happening here:
- We added an
idto the first script tag so we can easily update its content if needed. - The
showfunction is defined with a simple example—you'll want to replace this with your actual implementation that generates the result you want to display. - When the page loads, we automatically populate the input with the result of
show('Cat')to match the default dropdown option. - Every time you pick a new animal from the dropdown, the event listener triggers:
- It gets the selected animal's name.
- Runs your
showfunction with that name. - Puts the result straight into the input box.
- (Optional) Updates the line in the script tag that calls
show()to match the current selection—so your JavaScript code reflects what's currently running.
If you don't need to actually modify the visible JavaScript code (you just need to run the function and show the result), you can remove the part that updates scriptTag.textContent—the core functionality will still work perfectly.
内容的提问来源于stack exchange,提问作者Yan LimaBenua
相关产品推荐
相关产品推荐

