2012-03-09 63 views
2

我试图用jQuery查询web服务,并使用jquery模板将回复插入到我的html页面中。我的代码目前看起来像这样:将数据传递给匿名Javascript函数

$(function() { 
    $('.media-releases h3 div').click(function() { 

    var button = $(this); 
    if ($(this).hasClass("expand")) { 
     $(this).addClass("spinner"); 
     var params = '{ "year": "' + 2012 + '", "month": "' + 02 + '" }'; 

     $.ajax({ 
      type: "POST", 
      url: "NewsReleases.asmx/GetNewsReleases", 
      data: params, 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function (response) { 
       var result = jQuery.parseJSON(response.d); 
       $.get('NewsRelease.htm', function (data) { 
        // The problem is here, button is null. 
        // I assume I have to create a closure 
        // but I'm not sure how to do it. 
        var ul = button.parentNode.nextSibling; 
        $.tmpl(data, result).appendTo(ul); 
       }); 

       button.removeClass("spinner"); 
       button.parents('h3').next().slideDown(); 
       button.removeClass('expand').addClass('minimise'); 

      }, 
      error: function (error) { 
       /*Error handling code removed*/ 
      } 
     }); 

    } else { 
     button.parents('h3').next().slideUp(); 
     button.removeClass('minimise').addClass('expand'); 
    } 
}); 

});

如何使上述函数中的按钮变量可访问,以便我可以将模板附加到它上面?

+0

访问哪里? – Joseph 2012-03-09 08:27:03

回答

4

上面的代码应该工作已经因为success函数是在定义了button的上下文中创建的。

如果它不起作用,那么其他事情可能会中断。其他选项:

  • 检查错误控制台
  • 步骤通过代码在你的JS调试

[编辑]问题是button.parentNode; button是一个jQuery节点,而不是DOM节点(var button = $(this);)。改为使用button.parent()

+0

你是对的它不是按钮返回undefined它是按钮parentNode属性。如果我在Chrome中检查button.parentNode,它似乎填充得很好,但是在做var node = button.parentNode时它说未定义。任何想法为什么发生这种情况? – b3n 2012-03-09 08:40:13

+0

是的。你正在jquery节点上工作,而不是一个DOM节点('var button = $(this);')。试试'button.parent()'。 – 2012-03-09 08:43:46

+0

伟大的,这个作品。谢谢。 – b3n 2012-03-09 08:50:36

0

建立了对其他predifined函数的调用,这使你能够通过按钮作为参数 这会让你的成功:

success: function (response) { 
       onSuccess(response,button); 
      }, 

而新创建的功能将是这样的:

function onSuccess(response,button){ 
    var result = jQuery.parseJSON(response.d); 
        $.get('NewsRelease.htm', function (data) { 
         /*The problem is here, button is null. I assume I have to create a closure but I'm not sure how to do it.*/ 
         var ul = button.parentNode.nextSibling; 
         $.tmpl(data, result).appendTo(ul); 
        }); 

        button.removeClass("spinner"); 
        button.parents('h3').next().slideDown(); 
        button.removeClass('expand').addClass('minimise'); 
} 

Source

相关问题