无法获取下拉选中项对应数据值,出现Uncaught TypeError: Cannot use 'in' operator to search for 'length'错误求助
问题分析与修复方案
嘿,我来帮你搞定这个问题~你遇到的Uncaught TypeError错误,根源其实很简单:
错误原因
当你选择下拉框的选项时,$(this).val()返回的是单个字符串(比如选中Motorola时就是"Mobile-SmartPhone-Motorola"),但你却用jQuery.each()去遍历这个字符串。jQuery.each()处理字符串时,会把它当成类数组,逐个遍历每个字符,这就导致循环里的value变成了单个字符(比如'M'、'o'),自然在访问BestMobileJSON[value]时找不到对应属性,触发类型错误。
而且你的下拉框是单选的,本来就不需要遍历,直接拿选中的value去取对应数据就行。
修复后的完整代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <select id="BestMobileSelect"> <option></option> <option value="Mobile-SmartPhone-Motorola">Motorola</option> <option value="Mobile-SmartPhone-Samsung">Samsung</option> <option value="Mobile-SmartPhone-Xiaomi">Xiaomi</option> </select> <div id="BestMobileResult"></div> <script> jQuery(document).ready(function($) { var BestMobileJSON = { "Mobile-SmartPhone-Motorola": [{ "Price": "Rs.12000" }], "Mobile-SmartPhone-Samsung": [{ "Price": "Rs.15000" }], "Mobile-SmartPhone-Xiaomi": [{ "Price": "Rs.9000" }] } $("#BestMobileSelect").on("change", function() { var BestMobileSelected = $(this).val(); var markup = ''; // 先判断是否选中了有效选项 if(BestMobileSelected) { // 直接通过选中的value获取对应价格 markup += '<div>' + BestMobileJSON[BestMobileSelected][0].Price + '</div>'; } $("#BestMobileResult").html(markup); }); }); </script>
关键优化点
- 移除了多余的
jQuery.each()循环,因为单选下拉框每次只会返回一个选中值 - 增加了空值判断,避免选中第一个空选项时出现错误
- 给option的value属性加上了双引号,符合HTML规范(虽然浏览器能识别,但规范写法更稳妥)
内容的提问来源于stack exchange,提问作者Mithun Uchil
相关产品推荐
相关产品推荐

