代码之家  ›  专栏  ›  技术社区  ›  David 天宇 Wong

jqueryajax无法工作

  •  0
  • David 天宇 Wong  · 技术社区  · 15 年前

    嘿,我正在尝试在ajax请求之后更改div的html,ajax请求可以工作。数据是正确的,但选择器似乎找不到div

    这是密码

    $(".home .up_0").click(function(){
      $.post("includes/vote.php",   
            {
             truc : $(this).attr("id")
            },
           function(data){ 
            if(data=='fail') 
            {
              alert("Error.");
            }
            else
            {
              $(this).parents('.home').find('.score_neutre').html(data);
            }
           }
      );
    });
    
    3 回复  |  直到 15 年前
        1
  •  6
  •   DMI    15 年前

    这可能是因为 this 不是你所期望的内在功能。您需要添加一个变量来存储引用:

    $(".home .up_0").click(function(){
      var this_obj = $(this);
      $.post("includes/vote.php",   
            {
             truc : $(this).attr("id")
            },
           function(data){ 
            if(data=='fail') 
            {
              alert("Error.");
            }
            else
            {
              this_obj.parents('.home').find('.score_neutre').html(data);
            }
           }
      );
    });
    
        2
  •  1
  •   Doug Neiner    15 年前

    你的问题是 this

    这样做:

    $(".home .up_0").click(function(){
      var $this = $(this); // Cache the current `this` as a jQuery wrapped DOM element
      $.post("includes/vote.php",
           { truc : $(this).attr("id") },
           function(data){ 
              if(data=='fail') {
                  alert("Error.");
              } else {
                  // Reference the cached variable `$this`
                  $this.parents('.home').find('.score_neutre').html(data);
              }
           });
    });
    
        3
  •  0
  •   Fermin    15 年前

    这可能与 this 不代表 $(".home .up_0") function(data){} 成功功能?

    £('#Test').html(data);
    

    这会告诉你它是否有效。如果是,则需要使用var来存储 代表。