1

私は限られた 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();
    });

だから私の質問:どこから始めればいいですか?このような再利用可能な関数の作成について、どこで詳しく知ることができますか? または、本当に私を甘やかしたい場合、考えられる解決策またはヒントは何ですか?

時間をありがとう、ドラガン

4

3 に答える 3

1

これを試してください..動的にトリガーできるように

$("input:checkbox").change(function(){
  $(this).next('div').toggle();
});​
于 2012-10-02T10:03:58.280 に答える
1

セレクターを動的に構築することで、すべての要素を一度にターゲットにすることができます。

$('input[id^="e_"]').change(function() {
    $('#' + this.id + '_div').toggle();
});
于 2012-10-02T09:59:17.193 に答える
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>
于 2012-10-02T10:25:13.200 に答える