2012-03-09 93 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

相關問題