下拉菜单切回默认顶部选项时无法清除之前选中内容如何修复
问题原因
下拉菜单的默认提示选项What would you like to learn today?的value值为空,当你切回该选项时,选中值无法匹配JSON数据中的任意一条Question字段,不会执行内容覆盖逻辑,因此之前展示的关联信息会留存。
修复方法
在下拉菜单的change事件逻辑开头增加空值判断,选中值为空时直接清空信息展示区域即可,修改后的JS代码如下:
var jsonStringProcessing = '[{"Question":"Where would I find information on late trips?","Answer":"By using the Late Trip Application you can see incoming mail to your facility.","Link":"https://www.usps.com"},\ {"Question":"How many DPS errors will I have?","Answer":"Log into the application and drill down by zip 4 facility.","Link":"https://www.usps.com"},\ {"Question":"What should I do if im missing a trip?","Answer":"Login into the ___ application and drill down by facility.","Link":"https://www.usps.com"},\ {"Question":"What should I do if a load plan fails?","Answer":"Contact __ via the __ application","Link":"https://www.usps.com"},\ {"Question":"Where do I report late arriving trips?","Answer":"Click on the below hyper link to submit information.","Link":"https://www.usps.com"},\ {"Question":"How can I control work hours to plan?","Answer":"By logging into IVES and entering the appropriate information you can plan and schedule employees.","Link":"https://www.usps.com"}]'; var jsObjectProcessing = JSON.parse(jsonStringProcessing); // 填充processing下拉选项 $.each(jsObjectProcessing, function (key, val) { $("#processing").append("<option>" + val.Question + "</option>"); }); $("#processing").change(function () { var selectedItem = $(this).val(); // 新增空值判断,切回默认选项时清空内容 if (!selectedItem) { $("#listProcessing").empty(); return; } $.each(jsObjectProcessing, function () { if (this.Question == selectedItem) { $("#listProcessing").html( '<b>Answer:</b> ' + this.Answer + '<br>' + '<b>Link:</b> <a href="' + this.Link + '" target="_blank">' + this.Link + '</a>' ); } }); });
补充说明
你也可以根据需求在清空内容的位置填充自定义的默认提示文本,比如$("#listProcessing").text("请选择一个问题查看解答")。
内容的提问来源于stack exchange,提问作者tr303808
相关产品推荐
相关产品推荐

