如果选中复选框,则显示div [英] if check box is checked display div
问题描述
我想建立的东西像wordpress选项,用于在创建和文章时切换字段可见性。我构建的是依赖于 $。click
函数是切换父对象与相应的字段名称,我想知道什么是最好的方法这样做如果复选框被选中,因为我的代码将弄乱,如果你选中一个框,并重新加载页面,因为它的点击,而不是如果框实际上被选中。先感谢!
I'm trying to build something like wordpress options for toggling fields visibility when creating and article. What I've build is relying on the $.click
function that is toggling the parent with the corresponding field name and I was wondering what would be the best way of doing this with if the check box is checked because my code will mess up if you check a box and reload the page because its a click and not if the box is actually checked. Thanks in advance!
http://jsfiddle.net / zgrRd / 1 /
HTML
<input type="checkbox" name="title">
<span class="caption">Title</span>
<div class="hidden">
<h2>Title</h2>
<input type="text" name="title">
<span class="caption">Lorem</span>
</div>
jQuery
$('input[type="checkbox"]').click(function(){
var item = $(this).attr('name');
$('input[name="'+item+'"][type="text"]').parent().toggle();
});
推荐答案
假设您从外部控制复选框...
Assuming that you are externally controlling the checked state of your checkboxes...
演示: http://jsfiddle.net/zgrRd/ 5 /
换句话说,无论复选框处于何种状态,都会在页面加载时进行评估,因此如果未选中框,则相应的元素将开始隐藏。因此,如果您设置的值服务器端检查框,这个客户端JavaScript应该正确评估它。
In other words, whatever state the checkboxes are in will be evaluated when the page loads, so if a box is not checked, the corresponding element will start out hidden. So if you are setting a value server-side which checks the box, this client-side JavaScript should evaluate it properly.
function evaluate(){
var item = $(this);
var relatedItem = $("#" + item.attr("data-related-item")).parent();
if(item.is(":checked")){
relatedItem.fadeIn();
}else{
relatedItem.fadeOut();
}
}
$('input[type="checkbox"]').click(evaluate).each(evaluate);
HTML
HTML
<input type="checkbox" data-related-item="title1">
<span class="caption">Title</span>
<div class="hidden">
<h2>Title</h2>
<input type="text" id="title1">
<span class="caption">Lorem</span>
</div>
<hr>
<input type="checkbox" data-related-item="title2" checked>
<span class="caption">Title</span>
<div class="hidden">
<h2>Title</h2>
<input type="text" id="title2">
<span class="caption">Lorem</span>
</div>
注意我使用 data - *
属性。这避免使用一个字段的 name
属性来表示与另一个字段的关系。您可以合法地命名这些属性任何您想要的,只要它们的前缀为 data -
。
Note my use of data-*
attributes. This avoids using the name
attribute of one field to indicate a relationship to another field. You can legally name these attributes whatever you want, as long as they are prefixed with data-
.
这篇关于如果选中复选框,则显示div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!