2012-04-17 119 views
-1

如果我不勾选这两个框,此工作正常。不知道如何解决它。用复选框和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> 

http://jsfiddle.net/cip691/AeyAL/2/

+0

目前尚不清楚您期望的行为... – 2012-04-17 19:30:29

回答

1

试试这个:

$(".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

3

试试这个:

$(".home-check").live('click', function() { 
    $("li").hide(); 
    $(".home-check:checked").each(function() { 
     $("." + this.id).show(); 
    }); 
}); 

Example fiddle

注意:你的ID是围绕着错误的方式为标签,这就是为什么检查Fire显示水,反之亦然。

0
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(); 
} 
0

使用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(); 
    } 
});​ 
0

试试这个:

$(".home-check").live('click', function() { 
    if ($(this).is(':checked')) { 
     var ident = $(this).attr('id'); 
     $('.' + ident).hide(); 

    } else { 
     var identt = $(this).attr('id'); 
     $('.' + identt).show(); 
    } 

});

Example fiddle

0

http://jsfiddle.net/HKQxH/

这将显示和隐藏与复选框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> 

​