Jquery - 可重用的复选框功能

时间:2012-10-02 09:56:46

标签: jquery html forms

我凭借有限的JQuery知识遇到了困境, 我正在使用许多复选框:

    <input id="e_1" class="hiders" type="checkbox">
    <label for="e_1">Hide Element 1</label>

    <input id="e_2" class="hiders" type="checkbox">
    <label for="e_2">Hide Element 2</label>

    //Currently 6 of the above, with unique id's and shared class

我想创建一个通用(和可重用的函数)来隐藏相关的div:

    <div id="e_1_div"> content </div>

    <div id="e_2_div"> content </div>

    //Currently 6 of the above, with unique id's and shared class

以下解决方案是我目前正在使用的解决方案(每个复选框的单独功能),而我的有限知识告诉我它可怕的畸形,并且可能会耗尽大量不必要的功能。

    $('#e_1').change(function(){
       $('#e_1_div').toggle();
    });

    $('#e_2').change(function(){
       $('#e_2_div').toggle();
    });

所以我的问题:我从哪里开始?在哪里可以了解更多关于为此类内容创建可重用函数的信息? 或者,如果你真的想要破坏我,那么什么是可能的解决方案,或暗示它呢?

感谢您的时间, 德拉甘

3 个答案:

答案 0 :(得分:1)

您可以通过动态构建选择器来一次定位所有元素:

$('input[id^="e_"]').change(function() {
    $('#' + this.id + '_div').toggle();
});

答案 1 :(得分:1)

试试这个......这样你就可以动态地触发它

$("input:checkbox").change(function(){
  $(this).next('div').toggle();
});​

答案 2 :(得分:0)

请在下面找到简单的jquery脚本,它将完成所需的

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Toggle Checkbox</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){

    $(".hiders").change(function(){
        var currentId = $(this).attr('id');
        var divId = currentId+"_div";
        $("#"+divId).toggle();
    });

});
</script>

</head>

<body>

<input id="e_1" class="hiders" type="checkbox" /><label for="e_1">Hide Element 1</label>

<input id="e_2" class="hiders" type="checkbox" /><label for="e_2">Hide Element 2</label>

<div id="e_1_div">element - 1</div>

<div id="e_2_div">element - 2</div>

</body>
</html>