根据复选框选择显示/隐藏对象
问题描述:
我有一个包含一组复选框的页面,每个复选框都有一个动态生成的值,因此它随每个页面呈现而改变。样本是这样的:根据复选框选择显示/隐藏对象
<fieldset id="P163_PROFILES" tabindex="-1" class="checkbox_group">
<input type="checkbox" id="P163_PROFILES_0" name="p_v01" value="264" checked="checked">
<input type="checkbox" id="P163_PROFILES_1" name="p_v01" value="2356" checked="checked">
</fieldset>
我再有<div class="264">
和<div class="2356">
标签在整个页面的其余部分在该DIV类的输入值相匹配的日历布局。我的问题是这个。如果用户取消/检查其中一个输入框,我想隐藏/显示具有匹配类的DIV。由于我不熟悉jQuery,因此我正在努力识别已更改的输入对象,然后使用它的值来更改适当的DIV对象。这里是我到目前为止的代码:
<script type="text/javascript">
$('[id^=P163_PROFILES_]').click(function(){
var pClass = '.'+$(this).val();
if ($(this).is(':checked')) {
$(pClass).show;
} else {
$(pClass).hide;
}
});
</script>
我是否关闭?
感谢, 杰夫
答
你实际上是非常接近!你是show()
和hide()
方法后忘记()
:
if ($(this).is(':checked')) {
$(pClass).show();
} else {
$(pClass).hide();
}
答
你可能想
$('input[id^="P163_PROFILES_"]').click(function(event){
var pClass = '.'+$(event.target).val();
if ($(event.target).is(':checked')) {
$(pClass).show();
} else {
$(pClass).hide();
}
});
你可能不担心这样一个特定的冒泡选择器,所以你可以使用:
$('input[id^="P163_PROFILES_"]').click() {
var $this = $(this);
$('.'+$this.val()).toggle($this.is(':checked));
});
答
您应该可以简单地使用该代码。首先,我建议不要使用click()
事件,首选事件将是change()
首先,我们假设一切都以所需状态开始。你可以这样做:
<script type="text/javascript">
$('input[id^="P163_PROFILES_"]').change(function(){
var pClass = '.'+$(this).val();
$(pClass).toggle();
});
</script>
切换将简单地切换所选元素的可见性。
如果您需要根据状态来切换然后做这样的事情:
<script type="text/javascript">
$('input[id^="P163_PROFILES_"]').change(function(){
var pClass = '.'+$(this).val();
if ($(this).is(':checked'))
$(pClass).show();
else
$(pClass).hide();
});
</script>
答
其实你可以进一步简化它,如果你查询的字段集inputchildren而不是查询上的ID开始的。可能会简化您的代码,因为这可能意味着您不必为输入生成ID。
此外,你过度使用jQuery。通常“this”会包含所有你需要的东西,而且你不需要通过将它包装到jQuery中来增加开销。没有理由不直接使用this.checked和this.value afaik。
$('#P163_PROFILES > input').change(function(){
if (this.checked)
$('.'+this.value).show();
else
$('.'+this.value).hide();
//Or toggle if you know the initial state is in sync with the target
//and nothing else changes the show/hide of those targets.
//$('.'+this.value).toggle();
});