用复选框和jquery显示隐藏元素 - jsfiddle示例
问题描述:
如果我不勾选这两个框,此工作正常。不知道如何解决它。用复选框和jquery显示隐藏元素 - jsfiddle示例
$(".home-check").live('click', function() {
if ($(".home-check").is(':checked')) {
var ident = $(this).attr('id');
$('.' + ident).hide();
} else {
var identt = $(this).attr('id');
$('.' + identt).show();
}
});
<p><input class="home-check" id="water" type="checkbox" name="gethired" />Fire - Only Show Fire</p>
<p><input class="home-check" id="fire" type="checkbox" name="hire" />Water - Only Show Water</p>
<li class="fire">Fire</li>
<li class="water">Water</li>
<li class="fire">Fire</li>
<li class="water">Water</li>
<li class="fire">Fire</li>
<li class="water">Water</li>
答
试试这个:
$(".home-check").on('click', function() {
var li_class = '.' + this.id;
$(li_class).toggle();
});
不要在次使用活如果没有必要,请使用toggle而不是show和hide =编写更少的代码;)。和
代替
$(this).attr('id');
使用:
this.id
它会更快!
希望它有用!
+0
非常好。切换工作很好。谢谢! – Ciprian 2012-04-17 19:38:52
答
试试这个:
$(".home-check").live('click', function() {
$("li").hide();
$(".home-check:checked").each(function() {
$("." + this.id).show();
});
});
注意:你的ID是围绕着错误的方式为标签,这就是为什么检查Fire
显示水,反之亦然。
答
if ($(".home-check").is(':checked')) {
var ident = $(this).attr('id');
$('.' + ident).hide();
} else {
var identt = $(this).attr('id');
$('.' + identt).show();
}
你不假设你使用的是TAG的ID吗?所以改变“。”为 “#”,并尝试
if ($(".home-check").is(':checked')) {
var ident = $(this).attr('id');
$('#' + ident).hide();
} else {
var identt = $(this).attr('id');
$('#' + identt).show();
}
答
使用event object得到target object that initiated the event。通过这种方式,您可以直接对其执行操作,而不是执行搜索复选框,该复选框在您将它们都选中时返回两个项目。
$(".home-check").live('click', function (event) {
var checkbox = event.target;
var ident = $(checkbox).attr('id');
if ($(checkbox).is(':checked')) {
$('.' + ident).hide();
} else {
$('.' + ident).show();
}
});
答
试试这个:
$(".home-check").live('click', function() {
if ($(this).is(':checked')) {
var ident = $(this).attr('id');
$('.' + ident).hide();
} else {
var identt = $(this).attr('id');
$('.' + identt).show();
}
});
答
这将显示和隐藏与复选框li元素。
李必须隐藏(我猜)
li{display:none;}
的JS
$(".home-check").live('click', function() {
if ($(this).is(':checked')){
$('li.' + $(this).attr('id')).show();
}
else{
$('li.' + $(this).attr('id')).hide();
}
});
和HTML( “火” 和 “水” 不是 “命令”)
<p><input class="home-check" id="water" type="checkbox" name="gethired" />Water</p>
<p><input class="home-check" id="fire" type="checkbox" name="hire" />Fire</p>
<li class="fire">Fire</li>
<li class="water">Water</li>
<li class="fire">Fire</li>
<li class="water">Water</li>
<li class="fire">Fire</li>
<li class="water">Water</li>
目前尚不清楚您期望的行为... – 2012-04-17 19:30:29