当我尝试删除条目时,jQuery 出现奇怪的循环问题

发布于 2024-08-07 02:24:43 字数 5773 浏览 4 评论 0原文

我已尽力在代码中记录这一点。

当我尝试删除已添加的项目时,出现奇怪的循环问题。

示例:

我添加了 3 个项目:

  • 当我尝试删除第一个项目时 列表中的项目...我得到确认 删除对话框 3 次

  • 删除第二次 列表中的项目...我得到确认两次。

  • 是的...你猜对了..最后一个只给了我一次。

提前致谢。

无论如何,这是带注释的 jQuery 代码(这是一个很大的代码):

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

?>

I have tried to document this as well as I can in the code.

Getting a weird looping thing when I try to delete an item that I've added.

Example:

I have 3 items that I've added:

  • When I try to delete the very first
    item in the list...I get the confirm
    Delete dialog 3 times

  • Deleting the second
    item in the list...I get the confirm 2 times.

  • And yep...you guessed it..that last one gives it to me only once.

Thanks in advance.

Anyway, here's the commented jQuery code (it's a big one):

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

And the delete.php file:

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

?>

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

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

发布评论

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

评论(2

我想你想看看 jQuery 1.3 中的 live 函数,它自动绑定事件到新创建的元素。您需要将其完全移出帖子部分,以便它在第一页加载时运行。像这样的东西应该有效:

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

I think you want to look at the live function in jQuery 1.3, which automatically binds events to newly-created elements. You'll need to move it completely out of the post section so that it runs on the first page load. Something like this should work:

$(".del").live("click", function(){
  //event code here
});
箹锭⒈辈孓 2024-08-14 02:24:43

该行:

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

返回具有 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

The line:

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

is returning all the elements with a class of del which means every time you add a new item you're adding a new event to each existing del element. (Glancing at the rest of your code this is going to be an issue for most of your elements apparently).

Your best option is to assemble the elements that make up each new item individually and assign specific events to them before appending them to the content. That way you know each specific element will have a single correct even associated with it.

EDIT:

passing data to a new function:

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

Setting up a global variable:

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