2011-05-04 2 views
0

다음 코드는 JQuery, DOM에 있습니다. 실행 준비 완료입니다. 작업은 PHP 파일에 데이터를 게시하고 반환 된 데이터를 지정된 위치에 반환하는 것입니다. div. 나는 5 비트의 코드를 사용하고 있으며, 대부분은 스스로를 반복한다. 어떻게 든이 코드를 리팩토링하고 싶었습니다.이 코드를 몇 줄로 만들 수 있습니까?JQuery : 일부 Jquery 코드를 간단하고 쉽게 만들기 위해 리팩토링하고 싶습니다.

기본적으로 선택 상자 요소가 변경되면 코드가 실행되어 코드가 실행됩니다.

// 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'd에 없습니다.
기본적으로이 선택 상자를 사용하여 카테고리를 탐색하여 원하는 위치를 쉽게 시각화합니다. 카테고리 탐색에서. $ data 변수는 요청 된 카테고리 데이터의 배열을 가진 객체입니다.

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

아마 난 그냥 가입 코드 검토 http://codereview.stackexchange.com/ – CaffGeek

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

다음 함수로 전환해야 할 것 같습니다 (죄송 임 다른 좀 더 코드를 정리 한 것, 시간 G2G 작업에 누르면) 단지 올바른 선택기로 함수를 호출 (나는 그이 ...

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

이것은 내가 생각하고있는 것이지만, html로 이벤트에 첨부하는 데 문제가있어서, onchange = "LevelCategories (..."를 사용했지만 "#"기호로 작업하지 못했습니다.) – Anil

0

가 시작, 리팩토링을 수행 테스트는 functiona을 작은 잘못 확인 할 수 있습니다 유감은 동일하다, 반복한다. 간단한 리팩토링이 작업을 수행하는 것입니다 :

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

첫 번째 예제를 이해합니다. 하지만 정확히 어떻게 두 번째 예제를 사용할지 모르겠다. 선택 상자가 있는데, 선택 상자의 이벤트 스크립트 onchange의 원인을 파악하는 데 두 번째 예제를 어떻게 사용합니까? – Anil

+0

게시 한 전체 코드가 실행 된 것으로 가정합니다. 한 번에 선택 항목을 사용할 수 있었지만 지금은 그렇지 않다는 인상을 받기 시작했습니다. 더 자세한 정보 (예 : 어떤 요소가 있는지, 5 개의 코드 부분을 언제 실행할 수 있는지)를 제공 할 수 있다면 예제를 수정하고 더 잘 설명하십시오. – digibo

+0

첫 번째 글을 편집했습니다. – Anil

관련 문제