【问题标题】:tr didn't remove in ajax request.tr 没有在 ajax 请求中删除。
【发布时间】:2016-01-10 18:33:20
【问题描述】:

我正在尝试使用最接近的函数从表中删除 tr。 此函数在 $.post 请求中正常工作,但是当在 post 请求中使用相同的脚本时,它不起作用。 我的代码是

$(".delete_cat").click(function() {
        var idd = $(this).val();

        $.post("<?php echo base_url() ?>category/delete",
            {id:idd},
            function(data) {

                if (data === 1) {
                    var tr = $(this).closest('tr').remove();
                    tr.css("background-color","#FF3700");
                    tr.fadeOut(400, function(){
                        tr.remove();
                    });

                }
            }
            )

    })

【问题讨论】:

标签: javascript jquery ajax


【解决方案1】:

这是因为元素的上下文在 ajax 调用中丢失了。您可以使用 ajax 的上下文选项来设置单击的.delete-cart 元素的上下文:

   $.post("<?php echo base_url() ?>category/delete",
   {id:idd},
   context:this,
   function(data) {
     if (data === 1) {
         var tr = $(this).closest('tr').remove();
         tr.css("background-color","#FF3700");
         tr.fadeOut(400, function(){
         tr.remove();
     }
   });

Context option in ajax

【讨论】:

    【解决方案2】:

    thispost success 函数中有不同的实例

    $(".delete_cat").click(function() {
      var that = this
      var idd = $(that).val();
    
      $.post("<?php echo base_url() ?>category/delete", {
          id: idd
        },
        function(data) {
    
          if (data === 1) {
            var tr = $(that).closest('tr').remove();
            tr.css("background-color", "#FF3700");
            tr.fadeOut(400, function() {
              tr.remove();
            });
    
          }
        }
      )
    
    })

    【讨论】:

      【解决方案3】:

      $(this)内部函数不是引用.delete_cat,而是窗口,缓存那些:

      $(".delete_cat").click(function() {
         var $this = $(this);  // <----here
         var idd = $this.val();
      
          $.post("<?php echo base_url() ?>category/delete",
              {id:idd},
              function(data) {
                  if (data === 1) {
                      var tr = $this.closest('tr').remove();
                      tr.css("background-color","#FF3700");
                      tr.fadeOut(400, function(){
                          tr.remove();
                      });
                  }
         });
      });
      

      【讨论】:

      • .delete_cat 是动态元素吗?
      • 不,我的意思是,表是动态创建的吗?您是否尝试在点击处理程序上提醒某些内容?
      猜你喜欢
      • 1970-01-01
      • 2016-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多