我有以下脚本,如果选择国家/地区美国,则会显示州选择下拉列表。
<script type="text/javascript">
$(function() {
$('#country').change(function(){
$('.state').hide();
$('#' + $(this).val()).show();
});
});
</script>
<div class="large-6 columns">
<div class="input-wrapper">
<label>
Country
<select name="user_country" id="country">
<option selected disabled value=''>Select Country</option>
<option value="USA" <?php if ($_POST['user_country']=="USA") echo "selected"; ?>>United States</option>
<option value="United Kingdom" <?php if ($_POST['user_country']=="United Kingdom") echo "selected"; ?>>United Kingdom</option>
<option value="Ireland" <?php if ($_POST['user_country']=="Ireland") echo "selected"; ?>>Ireland</option>
</select>
</label>
</div>
</div>
</div>
<div id="USA" class="state" style="display:none">
<div class="row">
<div class="large-6 columns">
<div class="input-wrapper">
<label>
State
<select name="user_state">
<option selected disabled value=''>Select State</option>
<option value="AL" <?php if ($_POST['user_state']=="AL") echo "selected"; ?>>Alabama</option>
<option value="AK" <?php if ($_POST['user_state']=="AK") echo "selected"; ?>>Alaska</option>
<option value="AZ" <?php if ($_POST['user_state']=="AZ") echo "selected"; ?>>Arizona</option>
</select>
</label>
</div>
</div>
</div>
</div>
一切正常,但如果已选择美国,我试图让脚本在页面加载时运行。
任何想法如何实现这一目标?
非常感谢,
约翰
答案 0 :(得分:4)
你必须明确地触发它:
$(function() {
$('#country').change(function(){
$('.state').hide();
$('#' + $(this).val()).show();
}).trigger('change'); // <----- trigger the event here || or .change();
});
答案 1 :(得分:0)
$(function() {
var countrySel = $('#country');
updateCountry( countrySel.val() );
countrySel.on('change', function() { updateCountry( countrySel.val() ) );
});
updateCountry( val ) {
$('.state').hide();
$('#' + val).show();
}