Pergunta

Eu tentei documentar isso o melhor que posso no código.

Conseguir uma coisa estranha quando tento excluir um item que adicionei.

Exemplo:

Eu tenho 3 itens que adicionei:

  • Quando tento excluir o primeiro item da lista ... Recebo a caixa de diálogo Confirmar Excluir 3 vezes

  • Excluindo o segundo item da lista ... Recebo a confirmação 2 vezes.

  • E sim ... você adivinhou ... o último me dá apenas uma vez.

Desde já, obrigado.

Enfim, aqui está o código jQuery comentado (é grande):

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

E o arquivo 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);
}

?>
Foi útil?

Solução

Eu acho que você quer olhar para o viver Função no JQuery 1.3, que liga automaticamente eventos a elementos recém-criados. Você precisará movê -lo completamente para fora da seção de postagem para que ele seja executado na primeira página carregando. Algo assim deve funcionar:

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

Outras dicas

A linha:

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

está retornando todos os elementos com uma classe de del o que significa que toda vez que você adiciona um novo item que está adicionando um novo evento a cada del elemento. (Olhando para o restante do seu código, isso será um problema para a maioria dos seus elementos aparentemente).

Sua melhor opção é montar os elementos que compõem cada novo item individualmente e atribuem eventos específicos a eles antes de anexá -los ao conteúdo. Dessa forma, você sabe que cada elemento específico terá um único correto, mesmo associado a ele.

EDITAR:

Passando dados para uma nova função:

  $("#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
   }

Configurando uma variável global:

  $("#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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top