0

私は JQuery に次のコードを持っています。DOM Ready で実行されます。その仕事は、データを PHP ファイルに投稿し、返されたデータを指定された div に返すことです。私は 5 ビットのコードを使用していますが、そのほとんどは繰り返し使用されています。これをどうにかしてリファクタリングしたかったのですが、誰かがこのコードを数行にすることは可能ですか?

基本的に、選択ボックス要素を変更すると、実行されてコードが実行されます。

// First Level Categories
    $("#slct_firstCat").live("change", function(){
    $("#div_secondCat").fadeOut();
    $("#div_thirdCat").fadeOut();
    $("#div_fourthCat").fadeOut();
    $("#successCats").remove();

    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_firstCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 1},
        function(data){
            $("#div_secondCat").fadeIn().html(data);
           });
    // End of Function getCats
    });

// Second Level Categories
    $("#slct_secondCat").live("change", function(){
    $("#div_thirdCat").fadeOut();
    $("#div_fourthCat").fadeOut();
    $("#successCats").remove();

    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_secondCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 2},
        function(data){
            $("#div_thirdCat").fadeIn().html(data);
           });
    // End of Function getCats
    });


// Third Level Categories
    $("#slct_thirdCat").live("change", function(){
    $("#div_fourthCat").fadeOut();
    $("#successCats").remove();

    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_thirdCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 3},
        function(data){
            $("#div_fourthCat").fadeIn().html(data);
           });
    // End of Function getCats
    });

// Fourth Level Categories
    $("#slct_fourthCat").live("change", function(){
    $("#successCats").remove();

    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_fourthCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 4},
        function(data){
            $("#div_fourthCat").fadeIn().html(data);
           });
    // End of Function getCats
    });

// Fifth Level Categories
    $("#slct_fifthCat").live("change", function(){
    $("#successCats").remove();
    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_fifthCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 5},
        function(data){
            $("#div_fourthCat").fadeIn().html(data);
           });
    // End of Function getCats
    });

ほとんどのコードが何度も繰り返されていることがわかります。変更されるのは、ポスト アクションの要素名とカテゴリ レベルだけです。

JS スクリプトにこの大量のコードを何度も使用するのは嫌いです。可能であれば、誰かがこれを数行または関数に減らすのを手伝ってくれるでしょうか?

- - - - - - - - - - - - - - 編集 - - - - - - - - - - - -----

これが役立つ場合、これは $.post からデータを送り返す php コードです。
各選択ボックスは、html に投稿されたときに独自の div 内にあります。DIV は html 上にあり、ajax ではありません。
基本的に、これらの選択ボックスを使用してカテゴリに移動し、カテゴリ ナビゲーションのどこにいるかを簡単に視覚化したいと考えています。 . $data 変数は、要求されたカテゴリ データの配列を持つオブジェクトです。
(申し訳ありませんが、g2g の作業に追われています。そうでなければ、コードをもっとクリーンアップしていたはずです)

<?php if (isset($data->CategoryArray->Category->LeafCategory) == 1){ ?>

    <div id='successCats' align='center'>
    <b>Your Selected Category is:</b><br/>
    <select id='selectedCategory' name='selectedCategory' size='1'>
    <option value='<?=$data->CategoryArray->Category->CategoryID."'>".$data->CategoryArray->Category->CategoryName;?></option>
    </select>
    </div>

<?php } else {  ?>
<?php
$catLevel = $_POST['categoryLevel'];
if ($catLevel == 1){
    echo "<select id=\"slct_secondCat\" name=\"slct_secondCat\" size=\"15\">";
} elseif ($catLevel == 2) {
    echo "<select id=\"slct_thirdCat\" name=\"slct_thirdCat\" size=\"15\">";
}
  else if($catLevel == 3){
  echo "<select id=\"slct_fourthCat\" name=\"slct_fourthCat\" size=\"15\">";
} else if($catLevel == 4){
  echo "<select id=\"slct_fifthCat\" name=\"slct_fifthCat\" size=\"15\">";
}

    $cats = array_slice($data->CategoryArray->Category,1);
    foreach ($cats as $cats){
    if ($cats->CategoryID == $cats->CategoryParentID){
    // Do Nothing - Get rid of the first header Cat
    } else {
    $option =  "<option value=\"" . $cats->CategoryID . "\">" . $cats->CategoryName;
    if(!isset($cats->LeafCategory)){
        $option .= " >";
    }

    $option .= "</option>";

    echo $option;
    }
    } // End of For each

} // End of First If Else
?>
<?php echo "</select>"; ?>
4

2 に答える 2

1

しかし、このブロックを関数に変換する必要があるようです

function LevelCategories(levelSelector, levelSelector2) {
    $("#slct_secondCat").live("change", function(){
    $("#div_thirdCat").fadeOut();
    $("#div_fourthCat").fadeOut();
    $("#successCats").remove();

    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $(levelSelector).val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 2},
        function(data){
            $(levelSelector2).fadeIn().html(data);
           });
    // End of Function getCats
    });
}

次に、正しいセレクターを使用して関数を呼び出すだけです (それらが間違っている可能性があります...

LevelCategories("#slct_firstCat", "#slct_secondCat");
LevelCategories("#slct_secondCat", "#slct_thirdCat");
LevelCategories("#slct_thirdCat", "#slct_fourthCat");
LevelCategories("#slct_fourthCat", "#slct_fourthCat");
LevelCategories("#slct_fifthCat", "#slct_fourthCat");
于 2011-05-04T17:46:12.403 に答える
0

小さく始めて、リファクタリングを行い、機能が同じであることをテストして検証し、繰り返します。最も簡単なリファクタリングは、次のようにすることです。

function loadCategories($container, catId, level) {
    var actionRequested = "AJAX_getCats", url = "index.php";

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: level},
        function(data){
            $container.fadeIn().html(data);
    }); 
}

// First Level Categories
    $("#slct_firstCat").live("change", function(){
    $("#div_secondCat").fadeOut();
    $("#div_thirdCat").fadeOut();
    $("#div_fourthCat").fadeOut();
    $("#successCats").remove();

    var catId = $("#slct_firstCat").val();
    loadCategories($("#div_secondCat"), catId, 1);  
    // End of Function getCats
    });

// Second Level Categories
    $("#slct_secondCat").live("change", function(){
    $("#div_thirdCat").fadeOut();
    $("#div_fourthCat").fadeOut();
    $("#successCats").remove();

    var catId = $("#slct_secondCat").val();
    loadCategories($("#div_thirdCat"), catId, 2);   
    // End of Function getCats
    });


// Third Level Categories
    $("#slct_thirdCat").live("change", function(){
    $("#div_fourthCat").fadeOut();
    $("#successCats").remove();

    var catId = $("#slct_thirdCat").val();
    loadCategories($("#div_fourthCat"), catId, 3);  
    // End of Function getCats
    });

// Fourth Level Categories
    $("#slct_fourthCat").live("change", function(){
    $("#successCats").remove();

    var catId = $("#slct_fourthCat").val();
    loadCategories($("#div_fourthCat"), catId, 4);             
    // End of Function getCats
    });

// Fifth Level Categories
    $("#slct_fifthCat").live("change", function(){
    $("#successCats").remove();

    var catId = $("#slct_fifthCat").val();
    loadCategories($("#div_fourthCat"), catId, 5);
    // End of Function getCats
    });

もちろん、これは完璧にはほど遠いです。ここでの私のポイントは、自分でそれを行う方法を段階的に学ぶ必要があるということです。

編集:2回目のパスで、同じ機能を維持するために最善を尽くしました. コードはテストされていません:)

function loadCategories($container, catId, level) {
    var actionRequested = "AJAX_getCats", url = "index.php";

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: level},
        function(data){
            $container.fadeIn().html(data);
    }); 
}

var catSelects = [
        $("#slct_firstCat"),
        $("#slct_secondCat"),
        $("#slct_thirdCat"),
        $("#slct_fourthCat"),
        $("#slct_fifthCat")
];

var catDivs = [
        $(),
        $("#div_secondCat"),
        $("#div_thirdCat"),
        $("#div_fourthCat"),
];      

function attachChangeEvents() {
    $.each(catSelects, function(index) {
        var catIndex = index;
        this.live("change", function () {
            // Fade out other divs
            $.each(catDivs, function (divIndex) {
                if(divIndex > catIndex) {
                    catDivs[divIndex].fadeOut();
                }
            });

            $("#successCats").remove();         

            var nextLevel = catIndex+1,
            nextDiv = catDivs[Math.min(nextLevel, catDivs.length-1)];

            loadCategories(nextDiv, this.val(), nextLevel);                 
        });
    };          
};
于 2011-05-04T17:57:38.087 に答える