2011-03-03 2 views
0

내 프로젝트에는 사람, 작업, 순위와 같은 여러 목록이 있습니다. "사람"의 모든 인스턴스로, 당신이 볼 수 있듯이jQuery Delete : 유니버셜 또는 분리 함수?

$('dl.person li.delete').live("click", function() { 
    var personDL = $(this).closest('dl'); 

    if (confirm("Really delete person '" + personDL.find('dt').text() + "' ?")) { 
    $.ajax({ 
     type: "POST", 
     url: "/people/do-delete", 
     data: "person=" + personDL.attr('id'), 
     dataType: "json", 
     timeout: 8000, 
     success: function(data) { 
     personDL.fadeOut("slow", function() { 
      personDL.remove(); 
      var t = (data.total != 1) ? ' person' : ' persons'; 
      $('h3 span#people').text(data.total + t); 
     }); 
     } 
    }); 
    } 

    return false; 
}); 

, 각각의 목록을 작업 한 기능이 꽤 어려울 것 : 각 목록은, 나는 이런 식으로 뭔가를 보이는 별도의 jQuery 코드를 "직장"또는 "계급"으로 대체해야합니다.

단일 기능을 얻으려고합니까? (그 쉬운 방법이 있습니까?) 그대로 유지해야합니까?

답변

0

HTML과 URL 구조가 사람/직업/계급/etc.에 충분히 유사하다면 매우 간단한 일반 함수를 작성할 수 있습니다. 다음과 같은 내용 :

function initDeletes() { 

    var plurals = { 
     person: 'people', 
     job: 'jobs', 
     rank: 'ranks' 
    }; 

    $.each(['person', 'job', 'rank'], function (index, elt) { 
     $('dl.' + elt + ' li.delete').live('click', function() { 
      var $DL = $(this).closest('dl'); 
      var elts = plurals[elt]; 
      if (confirm("Really delete " + elt + " '" + $DL.find('dt').text() + "' ?")) { 
       $.ajax({ 
        type: 'POST', 
        url: '/' + elts + '/do-delete', 
        data: elt + '=' + $DL.attr('id'), 
        dataType: 'json', 
        timeout: 8000, 
        success: function(data) { 
         $DL.fadeOut('slow', function() { 
          $DL.remove(); 
          var t = ' ' + (data.total === 1 ? elt : elts); 

          // no need for a more-specific selector 
          // adding anything beyond an ID is overspecifying 
          $('#' + elts).text(data.total + t); 
         }); 
        } 
       }); 
      } 

      return false; 
     }); 
    }); 
}