简体   繁体   English

页面首次加载,选项未更新,如何解决?

[英]Page first load, options did not update, how to solve?

I have two selection fields; 我有两个选择字段;

<label>Color:</label>    
<select id="color">
    <option value="red">Red</option>
    <option value="blue">Blue</option>
</select>

<label>Car:</label>
<select id="car"></select>

I would like to implement the feature that if color " red " is selected, update the car selection options to be "red car 1" and "red car 2" . 我要实现的功能是,如果选择了颜色“ 红色 ”,请将car选择选项更新为“红色汽车1”“红色汽车2” If color " Blue " is selected, update the car options to be "blue car 1" and "blue car 2" . 如果选择了颜色“ 蓝色 ”,则将car选项更新为“蓝色汽车1”“蓝色汽车2”

I implement this feature in the following way: 我通过以下方式实现此功能:

var updateOptions = function(carField, options) {
    carField.empty();
    for (var i = 0; i < options.length; i++) {
        carField.append("<option value=" + options[i] + ">" + options[i] + "</option>");
    }

};

var colorField = $('#color');
var carField = $('#car');

colorField.change(function() {
    if (colorField.val() === 'red') updateOptions(carField, ['red car 1', 'red car 2']);
    else if (colorField.val() === 'blue') updateOptions(carField, ['blue car 1', 'blue car 2']);
});

Things are fine here. 这里的一切都很好。 The only problem is, the car selection options get updated only if user select the color . 唯一的问题是,仅当用户选择colorcar选择选项才会更新。 The page first load will not update the car selection options. 页面首次加载不会更新car选择选项。 For example, " red " color is the default selected color when page loaded, but the car field is empty after page get loaded. 例如,“ 红色 ”颜色是页面加载时的默认选定颜色,但是页面加载后,car字段为空。 How to get rid of this efficiently? 如何有效地摆脱这种情况?

Try adding this code: (outside any function) 尝试添加以下代码:(在任何函数之外)

$(document).ready(function() {
  $('#color').change();
});

While loading page make a call like this - 在加载页面时拨打这样的电话-

updateOptions(carField, ['red car 1','red car 2']); updateOptions(carField,['red car 1','red car 2']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM