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

发布于 2024-11-05 12:38:02 字数 4584 浏览 4 评论 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>"; ?>

I have the following code in JQuery, On DOM Ready it runs, its job is to post data to my PHP file, and return the returned data into the specified div. I am using 5 bits of code, most of it is repeating it self over again. I wanted to refactor this somehow, can someone make this code into a couple of lines is possible?

Basically, on change of a select box element, it runs and does the code.

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

You can see most the code is repeated many times, the only things that change are the element names and the category level in the post action.

I hate having this huge chunk of code in my JS script, used over and over again, surely someone out-there can help reduce this to a few lines or a function if possible?

--------------------------- EDIT ---------------------------

This is the php code that sends the data back from the $.post, if this helps.
Each select box is inside its own div when posted to html, The DIVs are on the html and not ajax'd in.
Basically, I want to navigate down to a category using these select box's to easily visualize where I am in the category nav. The $data variable, is an object which has an array of the category data requested.
(Sorry Im pressed for time g2g work, else I would have cleaned up the code more)

<?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>"; ?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情绪少女 2024-11-12 12:38:02

但看起来这个块只需要变成一个函数

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

But it looks like this block just needs to be turned into a function

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

Then just call the function with the correct selectors (I may have those wrong...

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");
孤独患者 2024-11-12 12:38:02

从小处开始,进行一些重构,测试以验证功能是否相同,然后进行迭代。最简单的重构就是这样做:

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

Start small, do some refactoring, test to verify the functionality is the same, iterate. The simplest refactoring would be to do this:

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

Of course this is far from perfect - my point here is you should learn to do it yourself, step by step.

Edit: Second pass and I did my best to keep the same functionality. The code is NOT tested:)

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);                 
        });
    };          
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文