2009-10-02 4 views
1

나는 이것을 코드화 할 수있을뿐만 아니라 문서화하려고 시도했습니다.jQuery에서 엔트리를 삭제하려고 할 때 이상한 루핑 문제가 발생했습니다.

내가 추가 한 항목을 삭제하려고하면 이상한 반복문을 얻습니다.

예 :

내가 추가 한 3 개 항목이 있습니다

  • 나는이 목록의 첫 번째 항목을 삭제하려고 할 때 ... 나는 확인을받을를 대화 삭제 3 번

  • 두 번째 항목을 삭제하는 중 ... 확인을 2 번받습니다.

  • 그리고 ... 네가 짐작했다. 마지막 한 번만 나에게 그것을 준다.

미리 감사드립니다.

$(document).ready(function() { 

    //hides the message/error console 
    $("#console").hide(); 

//this is the add new button functionality 
    $("#save").click(function(){ 
    var ul = $("ul.addul"); 
    var addM = $(".mo").val(); 
    var addY = $(".yr").val(); 
    var addC = $(".ct").val(); 
    var addT = $("textarea#addThoughts").val(); 

    //submit the add 
    $.post("save.php", { month : addM, year : addY, cottage : addC, thoughts : addT }, 
     function(data){ 

     //all good 
     if(data.success) { 

      //returns the item's respective id from db 
      var returnID = data.id; 

      //resets the form after items inserted into db 
      document.getElementById('items').reset(); 

      //this puts the added item into the html 
      $(".added").append(//content in here removed to shorten the example); 

      //not implemented yet 
      $(".edit").click(function(){ 
      $(this).parent().siblings("li.addit").hide(); 
      $(this).parent().siblings("li").children("[name=month], [name=year], [name=cottage], [name=thoughts]").show(); 
      $(this).parent().siblings("li").children(".showDataMonth, .showDataYear, .showDataCottage, .showDataThoughts").hide(); 
      $(this).siblings(".del").hide(); 
      $(this).siblings(".cancel, .save").show(); 
      $(this).hide(); 
      }); 

      //this is functioning properly; this cancels an update 
      $("button.cancel").click(function(){ 
      $(this).parent().siblings("li.addit").show(); 
      $(this).parent().siblings("li").children("[name=month], [name=year], [name=cottage], [name=thoughts]").hide(); 
      $(this).parent().siblings("li").children(".showDataMonth, .showDataYear, .showDataCottage, .showDataThoughts").show(); 
      $(this).siblings(".edit, .del").show(); 
      $(this).siblings(".save").hide(); 
      $(this).hide(); 
      }); 

      //resetting of values to prepare another entry 
      $(".save, .cancel, .month, .year, .cottage, .thoughts").hide(); 
      $(".showDataThoughts").css({ width : "160px;"}); 
      $(".mo, .yr, .ct").val("0"); 

      //shows successful insert of data into db 
      $("#console").html(data.message).css({background: "green", color: "white"}).fadeIn().animate({ opacity : "+=0" }, 2000).fadeOut(); 

      //this is the delete function that I am referring to. 
      //I get the "confirm" dialog just fine. 
      //say I have 3 entries: 
      //if I try to delete the first entry...I get the confirm delete dialog 3 times. 
      //if I try to delete the second entry...I get the confirm delete dialog 2 times. 
      //and the 3rd entry...I only get it once. 
      //I'm stuck in a weird kinda loop. 
      $(".del").click(function(){ 
       var del = this; 
       var thisVal = $(del).val(); 
       $.post("delete.php", { dirID : thisVal }, 
       function(data){ 
       if(confirm("Are you sure you want to DELETE this entry?") == true) { 
        if(data.success) { 
        alert(thisVal); 
        } 
       } 
       return false; 
       }, "json"); 
      }); 

     } else if(data.error) { //item could not be added 
      $("#console").html(data.message).css({background: "red", color: "white"}).fadeIn().animate({ opacity : "+=0" }, 2000).fadeOut(); 
     } 
    }, "json"); 
    return false; 
}); //end of add button 

//this populates the select boxes 
$.getJSON('dates_in_residence.php', function(data){ 
    var htmlMonth = ''; 
    var htmlYear = ''; 
    var htmlCottage = ''; 
    var len = data.length; 
    for (var i = 0; i < 12; i++) {htmlMonth += '<option class="optionMonth" value="' + data[i].month + '">' + data[i].month + '</option>'; 
    } 
    $('select#addMonth').append(htmlMonth); 
    for (var i = 12; i < 34; i++) {htmlYear += '<option class="optionYear" value="' + data[i].year + '">' + data[i].year + '</option>'; 
    } 
    $('select#addYear').append(htmlYear); 
    for (var i = 35; i < 42; i++) {htmlCottage += '<option class="optionCottage" value="' + data[i].cottage + '">' + data[i].cottage + '</option>'; 
    } 
    $('select#addCottage').append(htmlCottage); 
}); 

//this adds select menu's value to hidden inputs 
$("#addMonth").change(function() { 
      var str = ''; 
      $("#addMonth option:selected").each(function() { 
       str += $(this).text() + " "; 
       }); 
      $(".mo").val(str); 
     }).change(); 
$("#addYear").change(function() { 
      var str = ""; 
      $("#addYear option:selected").each(function() { 
       str += $(this).text() + " "; 
       }); 
      $(".yr").val(str); 
     }).change(); 
$("#addCottage").change(function() { 
      var str = ""; 
      $("#addCottage option:selected").each(function() { 
       str += $(this).text() + " "; 
       }); 
      $(".ct").val(str); 
     }).change(); 
}); 

그리고 delete.php 파일 :

<?php 

if($_POST) { 

    $data['delID'] = $_POST['dirID']; 

    $query = "DELETE from //tablename WHERE dirID = '{$data['delID']}' LIMIT 1"; 

    $result = $db->query($query); 

    if($result) { 
    $data['success'] = true; 
    $data['message'] = "This entry was successfully removed."; 
    } 

    echo json_encode($data); 
} 

?> 

답변

1

난 당신이 jQuery를 1.3에서 live 기능을보고 싶은 생각을 새로운 기능으로 데이터를 전달

새로 만든 요소에 이벤트를 자동으로 바인딩합니다. 첫 번째 페이지로드에서 실행되도록 게시물 섹션 밖으로 완전히 이동해야합니다. 이 같은 것이 작동해야합니다 :

$(".del").live("click", function(){ 
    //event code here 
}); 
+0

"라이브"기능에 대해 궁금 해서요 ... 시도해 보겠습니다. 감사! – Scott

+0

전적으로 매력처럼 작동했습니다! 정말 고마워. – Scott

+0

"삭제"기능을 "저장"기능 밖으로 이동하는 방법이 있어야한다는 것을 알고있었습니다. 완전한! – Scott

1

가 라인 :

$(".del").click(function(){ 

어쨌든

, 여기에 주석 jQuery 코드 (그것은 큰 하나) 것 del 클래스의 모든 요소를 ​​반환하면 새 항목을 추가 할 때마다 추가된다는 의미입니다. 기존의 각 요소 del에 새 이벤트를 보내십시오. (나머지 코드를 보면 이는 대부분의 요소에서 분명히 문제가 될 것입니다.)

가장 좋은 방법은 각각의 새 항목을 개별적으로 구성하는 요소를 조합하고 해당 내용을 콘텐츠에 추가하기 전에 특정 이벤트를 할당하는 것입니다. 그렇게하면 각 특정 요소가 올바른 올바른 단일 요소를 갖게됩니다.

편집 :

$("#save").click(function(){ 
    var ul = $("ul.addul"); 
    var addM = $(".mo").val(); 
    var addY = $(".yr").val(); 
    var addC = $(".ct").val(); 
    var addT = $("textarea#addThoughts").val(); 

    //submit the add 
    $.post("save.php", { month : addM, year : addY, cottage : addC, thoughts : addT }, 
     function(data){ 

     //all good 
      if(data.success) { 
      run_success(data); 
      } 
     }//close function 
    }//close #save click 

    //new, global function 
    function run_success(data) { 
     //do things with data here 
    } 

전역 변수 설정 :

$("#save").click(function(){ 
    var ul = $("ul.addul"); 
    var addM = $(".mo").val(); 
    var addY = $(".yr").val(); 
    var addC = $(".ct").val(); 
    var addT = $("textarea#addThoughts").val(); 

    //submit the add 
    $.post("save.php", { month : addM, year : addY, cottage : addC, thoughts : addT }, 
     function(data){ 

     //all good 
      if(data.success) { 
      my_global_var = data; //note, my_global_var is created without a var 
            //before it, thereby assigning it a global scope 
      } 
     }//close function 
    }//close #save click 
+0

"저장"기능에서 "삭제"및 "편집"기능을 이동할 수 있습니까? – Scott

+0

그 문제가 해결되지 않을 겁니다. 클릭 이벤트가 클래스 선택기에서 반환 한 객체 목록이 아닌 특정 요소에 연결되도록 다시 작성해야합니다. – Steerpike

+0

"데이터"값을 가져올 방법이 있습니까? "저장"기능에서 빠져 나왔어? 다른 곳에서 사용 하시겠습니까? 감사. – Scott

관련 문제