2013-02-12 55 views
0

我拥有多套复选框,显示/隐藏基于该复选框被选中上一个div的。这可以用ID来完成,但我会在同一页面上多组的这些,需要一个更通用的选择,如类或选择最接近元素的复选框。显示/使用复选框隐藏最接近格

也许有人知道这是为什么不正确选择或知道一个更好的办法? http://jsfiddle.net/infatti/h3rh7/

$('.check-hide-show-content').hide(); // hide all content divs 

// begin show/hide 
$('.check-hide-show input:checkbox').click(function() { 

    $(this).parent().next('.check-hide-show-content').show(); 


    $(".check-hide-show input[type='checkbox']").not(this).prop("checked", false); // uncheck the other checkbox when this is checked 
}); 

回答

1

很简单:

$('.check-hide-show-content').hide(); // hide all content divs 

// begin show/hide 
$('.check-hide-show input:checkbox').change(function() { 
    $('.check-hide-show-content').hide().eq($(this).index('.check-hide-show input:checkbox')).show(); 
    $(".check-hide-show input[type='checkbox']").not(this).prop("checked", false); // uncheck the other checkbox when this is checked 
}); 
+0

尼斯。这工作。我不知道.eq和.index? – simple 2013-02-12 23:42:11

+0

这首先隐藏了它们,然后使用eq()使用所匹配的复选框的索引找到基于0的元素。您必须将索引放入索引中,因为它们都位于其他元素内,而“this”发现该索引已被检查。 – 2013-02-12 23:53:11

0

如果你想在客户端只能检查一个元素,你可以使用输入型收音机。

<form> 
<input type="radio" name="check" id="radio1"></input> 
<input type="radio" name="check" id="radio2"></input> 
</form> 

请务必给予属于共同拥有同一个名字收音机!

+0

不是一种选择。必须使用复选框,以便在用户选择选项之前不显示任何内容。 – simple 2013-02-12 23:21:18

0

也许这就是你想要什么 - http://jsfiddle.net/FloydPink/VL7Vx/1/

$('.check-hide-show-content').hide(); // hide all content divs 

// begin show/hide 
$('.check-hide-show input:checkbox').click(function() { 
    $('.check-hide-show-content').hide(); // hide all content divs 
    $('.' + $(this).val()).show(); 
    $(".check-hide-show input[type='checkbox']").not(this).prop("checked", false); // uncheck the other checkbox when this is checked 
}); 

请注意,我已经修改了您的标记,以及通过向内容添加div的,新的CSS类(option1option2),其请遵循复选框中的值。这是将复选框绑定到相应的div的一种方法。

在你的代码中,你试图从复选框中使用'$(this).parent()。next('.check-hide-show-content')'来获取div,这将不会成功,因为内容div不在该选择器指定的级别。

+0

不是。将会有多套这些。检查更新的小提琴。所以使用ID或值选择器并不是真正的选择。需要选择下一个最接近的div来隔离这个集合。 – simple 2013-02-12 23:25:29

1

有关使用输入上的HTML data attributes,并通过ID定位的div什么?我在这里一起引发一个简单的例子:http://jsfiddle.net/mRZYf/

+0

同样,不能使用IDS。认为50套这些是动态编写的。 – simple 2013-02-12 23:40:17