基于下拉选项显示/隐藏Div功能异常排查求助
Let's break down what's wrong with your current code and fix it step by step:
1. Root Causes of Your Issue
- Unreliable
<option>onclickevents: Browsers don’t consistently triggeronclickon dropdown options. The standard, cross-browser way to handle selection changes is to listen to the<select>element’sonchangeevent instead. - Unused
myfun()function: Your<select>hasonchange="myfun()"defined, but this function doesn’t exist anywhere. So no code runs when you switch to other options. - Incorrect toggle logic: Your
weg()function only flips the div’s current display state, rather than checking which option is selected. That’s why the div only reappears when you re-select "Soort behandeling" — it’s just toggling, not following your explicit requirement.
2. Fixed Code Implementation
First, update your HTML to remove the unreliable option onclick and bind the correct handler to the select’s onchange:
<select name="cars" class="" style="border:0px;border-bottom:1px solid #b70000;margin-left: 128px;width:200px;" id="state" onchange="handleTreatmentChange()"> <option value="behandeling" selected>Soort behandeling</option> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="fiat">Fiat</option> <option value="audi">Audi</option> </select> <div id="wegwezen"><p><b>Behandeling:</b> <span id="pr"></span> €00,00</p></div>
Then replace your JavaScript with this function that explicitly enforces your requirement:
// Initialize div state on page load (since "Soort behandeling" is selected by default) window.addEventListener('load', function() { const wegwezenDiv = document.getElementById('wegwezen'); wegwezenDiv.style.display = 'none'; }); function handleTreatmentChange() { const selectedValue = document.getElementById('state').value; const wegwezenDiv = document.getElementById('wegwezen'); // Hide if "Soort behandeling" is selected; show for all other options if (selectedValue === 'behandeling') { wegwezenDiv.style.display = 'none'; } else { wegwezenDiv.style.display = 'block'; } }
3. Better Practice: Separate Style from Logic
For cleaner, more maintainable code, use CSS classes instead of directly manipulating the style property:
Add this CSS:
.hidden { display: none; }
Update your div to include the default hidden class:
<div id="wegwezen" class="hidden"><p><b>Behandeling:</b> <span id="pr"></span> €00,00</p></div>
Modify the JS function to toggle the class instead:
function handleTreatmentChange() { const selectedValue = document.getElementById('state').value; const wegwezenDiv = document.getElementById('wegwezen'); if (selectedValue === 'behandeling') { wegwezenDiv.classList.add('hidden'); } else { wegwezenDiv.classList.remove('hidden'); } }
This approach lets you adjust hiding behavior (like using opacity or visibility instead of display) just by updating the CSS, without touching your JavaScript.
内容的提问来源于stack exchange,提问作者J. Coderino

