为什么我的JavaScript无法根据品牌选择切换图片显示/隐藏?
Let's walk through the small but critical issues in your code that are preventing the logo toggle from working correctly:
1. jQuery Load Order is Backwards
Your custom script runs before jQuery is loaded, so the $ variable doesn't exist yet. Always place the jQuery CDN script above your custom JavaScript code.
2. Duplicate IDs Break Event Binding
You have three <select> elements all using id="vehiclemake". HTML IDs must be unique—browsers will only attach the change event to the first element with that ID, ignoring the others. Rename the model and year selects to unique IDs like vehiclemodel and vehicleyear.
3. Missing # in Selector
In your else clause, you wrote $("bmwlogo") instead of $("#bmwlogo"). Without the #, jQuery looks for a non-existent <bmwlogo> tag instead of the element with that ID.
4. Logo Isn't Hidden By Default
The BMW logo shows up on page load by default. You need to set its initial state to hidden, either with inline CSS or a jQuery hide() call on page ready.
Fixed Full Code
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { // Hide logo on page load $("#bmwlogo").hide(); $('#vehiclemake').on('change', function() { if (this.value == 'BMW') { $("#bmwlogo").show(); } else { $("#bmwlogo").hide(); // Fixed selector here } }); }); </script> <div class="block-content"> <div class="level"> <select id="vehiclemake" class="ymm-select" name="_make"> <option value="">-- Make --</option> <option value="BMW" selected="">BMW</option> </select> </div> <div class="level"> <!-- Fixed unique ID --> <select id="vehiclemodel" class="ymm-select" name="_model"> <option value="">-- Model --</option> <option value="3-Series saloon (E21) 315 (1573 cm³, 75 PS)">3-Series saloon (E21) 315 (1573 cm³, 75 PS)</option> </select> </div> <div class="level"> <!-- Fixed unique ID --> <select id="vehicleyear" class="ymm-select" name="_year"> <option value="">-- Year --</option> </select> </div> <div class="ymm-clear"> </div> <div class="ymm-extra" style="display:none"> <div class="ymm-category-container"> <div class="ymm-clear"> </div> </div> <div class="ymm-search"> <div class="ymm-or-search"> Or search: </div> <form action="#"> <table width="100%"> <tbody> <tr> <td class="ymm-td-input" hidden=""> <input class="input-text ymm-search-field" type="text" name="s" value=""> </td> <td class="ymm-td-button" hidden=""> <button type="submit" title="Search" class="button"><span><span>Search</span></span></button> </td> </tr> </tbody> </table> </form> </div> </div> <button type="button" title="Search" class="button ymm-submit-any-selection">Search</button> </div> <div id="vehicle_selector_selections"> <!-- Added inline style to hide by default (matches jQuery hide()) --> <img id="bmwlogo" src="https://placehold.it/150x150?text=BMW_LOGO" style="display:none"> <p></p> </div>
内容的提问来源于stack exchange,提问作者Shaun Barratt

