未选择选项

时间:2019-01-03 15:06:51

标签: javascript jquery

我正在尝试选择以下两个选择中的特定选项:

<select class="crs-country form-control required" name="country" id="customer-state" data-region-id="customer-region"></select>

<select id="customer-region" name="region" class="form-control required"></select>

使用以下代码:

$(document).ready(function() {
  $('#customer-state option[value="Italy"]').prop("selected", true);
  $('#customer-region option[value="Liguria"]').prop("selected", true);
})

,但是没有机会使它正常工作。我还创建了JSFIDDLE

$(document).ready(function() {
  $('#customer-state option[value="Italy"]').prop("selected", true);
  $('#customer-region option[value="Liguria"]').prop("selected", true);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://country-regions.github.io/country-region-selector/crs.min.js"></script>

<select class="crs-country form-control required" name="country" id="customer-state" data-region-id="customer-region"></select>

<select id="customer-region" name="region" class="form-control required"></select>

1 个答案:

答案 0 :(得分:3)

这可能是因为您加载的crs.min.js插件依赖于监听onchange元素上的<select>事件来更新区域下拉列表。因此,如果您在父onchange元素上手动触发/调度<select>事件,那么它应该可以工作:

$(document).ready(function() {
  $('#customer-state option[value="Italy"]').prop("selected", true).parent().trigger('change');
  $('#customer-region option[value="Liguria"]').prop("selected", true);
})
<script src="http://country-regions.github.io/country-region-selector/crs.min.js" id="crs"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="crs-country form-control required" name="country" id="customer-state" data-region-id="customer-region"></select>

<select id="customer-region" name="region" class="form-control required"></select>

更好:实际上,您不需要使用jQuery选择<option>元素:您只需将<select>元素的值设置为所需的选定选项,然后正确的<option>将被自动选择。我更喜欢这种方法,因为它使您的代码更具可读性,并且性能更高一些,因为浏览器不必遍历所有嵌套的<option>元素即可匹配属性选择器:

$(document).ready(function() {
  $('#customer-state').val('Italy').trigger('change');
  $('#customer-region').val('Liguria');
})
<script src="http://country-regions.github.io/country-region-selector/crs.min.js" id="crs"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="crs-country form-control required" name="country" id="customer-state" data-region-id="customer-region"></select>

<select id="customer-region" name="region" class="form-control required"></select>