JQuery:想要重构一些Jquery代码,使其简单易用

时间:2011-05-04 17:35:47

标签: jquery refactoring jquery-post

我在JQuery中有以下代码,在DOM就绪它运行,它的工作是将数据发布到我的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>"; ?>

2 个答案:

答案 0 :(得分: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");

答案 1 :(得分: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
    });

当然这远非完美 - 我的观点是你应该学会自己一步一步地去做。

编辑:第二遍,我尽力保持相同的功能。代码未经过测试:)

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