【问题标题】:Select parent of $.ajax Jquery?选择 $.ajax Jquery 的父级?
【发布时间】:2012-02-17 13:08:03
【问题描述】:

如何选择 $.ajax 的父元素或触发 $.ajax 的元素的父元素。我需要某种参考,以便将结果数据应用到它:

var a = $a.val();
var b = $b.val();

 $.ajax({
      type: "POST",
      url: "/Controller/Action",
      data: { a: a, b: b },
      success: function (data) {

          var values = data.values,
              $elements = $();
              for (i = 0; i < 142; i++) {
                  $elements = $elements.add($("<div class='single'>").css('height', values[i]).css('margin-top', 26 - valuesG[i]));
              }
                //Here it should reference $(this).parent().parent().. something
               //and not :last, because there are many .second elems... 
              //not only :last is being changed?

              $elements.appendTo($(".second:last"));
              $(".second:last").children(".single").addClass("ui-selected");
      },
      traditional: true
});   

$(this).parent()在ajax成功函数中返回jQuery() 有什么想法吗?

【问题讨论】:

    标签: javascript jquery ajax jquery-ui jquery-selectors


    【解决方案1】:

    使用上下文选项:

    $.ajax({
        url: "test.html",
        context: document.body,
        success: function(){
          $(this).addClass("done");
       }
    });
    

    jQuery Reference

    【讨论】:

    • 上下文:这个,应该做!谢谢!
    【解决方案2】:

    因为默认情况下ajax 调用是asynch,所以当您在success 中执行$(this) 时,this 引用ajax api 等$(this).parent() 引用jQuery()

    为了避免这种情况,在 ajax 调用开始在 success 中使用之前,将 element reference 保存在 variable 中。

    target_element = $(this);
    
    $.ajax({
          type: "POST",
          url: "/Controller/Action",
          data: { a: a, b: b },
          success: function (data) {
           // ....................
                   target_element.parent()
         ...............................
    

    【讨论】:

      【解决方案3】:

      把ajax的调用放到一个函数中,并将一个元素参数传递给函数?

      function doAjax(triggerElement)
      {
         $.ajax({
            url: whatever,
            context: triggerElement,
            success : function (content) { $(this).html(content);  }
         });
      }
      
      $(function () {
      
         $('#triggerElementId').click(function () { doAjax(this); });
      
      });
      

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 2011-03-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-28
        • 1970-01-01
        • 2019-11-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多