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

您可以看到大部分代码重复了很多次,唯一改变的是 post 操作中的元素名称和类别级别。

我讨厌在我的 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
    });

当然这远非完美——我的意思是你应该学会自己做,一步一步。

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

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 回答