我有这个设置:
<select id="status" name="status">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
</select>
<div id="additional_information" class="hidden">
Additional information
</div>
var val = $("#status option:selected").val();
if (val == '1') {
$('#additional_information').removeClass('hidden');
} else {
$('#additional_information').addClass('hidden');
}
当页面打开时,jQuery读取值并显示或隐藏隐藏的div。 但是,如果我更改了选项选项,它就不会再进行更改了。
如何让它工作以便在页面加载时加载值,然后每次用户在select中选择一个选项时相应地更改它?
答案 0 :(得分:3)
这里我使用了更改事件并触发了它也加载了
简化了代码
$(function() {
$("#status").on("change", function() {
// hide if this.value == 2 or use !=1 if there are more than 2 options
$('#additional_information').toggleClass('hidden', this.value == 2);
}).change(); // trigger to hide or show on load
})
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="status" name="status">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
</select>
<div id="additional_information" class="hidden">
Additional information
</div>
答案 1 :(得分:1)
您可以使用change
事件:
$('#status').on('change', function() {
if (this.value == '1') {
$('#additional_information').removeClass('hidden');
} else {
$('#additional_information').addClass('hidden');
}
}).change();
&#13;
.hidden {
display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="status" name="status">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
</select>
<div id="additional_information" class="hidden">
Additional information
</div>
&#13;
答案 2 :(得分:1)
将您的代码添加到分离的函数中然后在ready
和change
上调用它,如:
$(function(){
//For the first load
show_hide();
//For the user change on the status select
$('#status').on('change', show_hide);
})
function show_hide(){
var val = $("#status option:selected").val();
if (val == '1') {
$('#additional_information').removeClass('hidden');
} else {
$('#additional_information').addClass('hidden');
}
}
&#13;
.hidden{
display:none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='status'>
<option value='1'>With additional information</option>
<option value='2'>Without additional information</option>
</select>
<br><br>
<div id="additional_information">
Additional information
</div>
&#13;
希望这有帮助。
答案 3 :(得分:1)
你需要有一个事件处理程序,如下所示:
使用Javascript:
$("#status").on("change", function() {
$('#additional_information').toggleClass('hidden', this.value != 1);
});
$("#status").trigger("change");
答案 4 :(得分:1)
要让它检测页面何时加载以及何时更改,请添加.change()
事件处理程序并在页面加载时手动触发它:
$("#status").change(function() {
var val = $("#status option:selected").val();
if (val == '1') {
$('#additional_information').removeClass('hidden');
} else {
$('#additional_information').addClass('hidden');
}
}).change()
<强> jsFiddle example 强>