2011-04-08 184 views
2

我不知道爲什麼$(this).data()在按鈕單擊事件處理程序中返回null,但在螢火蟲中調試時,​​返回我期望的數據。

for (var i = 0; i < options.AvailableOperations.length; i++) { 
     var operation = options.AvailableOperations[i]; 
     var button = $(this).find("#btn" + operation); 
     button.data("operation", operation); 
     button.data("entityId", options.entityId); 
     button.parent().removeClass('disabledRevButton'); 

     var data = { operation: operation, entityId: options.entityId }; 
     button.click(function() { 

      $.postJson({ 
       url: GlobalVars.perfomDFOperation, 
       data: $(this).data(), 
       success: function (data) { 
        if (data != null) { 
         if (data.IsSuccess && data.RefreshPage) { 
          location.reload(true); 
         } 
         else if (!data.isSuccess) { 
          alert("error: " + data.Message) 
         } 
        } 
       } 
      }); 
     }); 
    } 

回答

1

this可能不指按鈕本身了,因爲它是$.postJson()範圍內了。

您可能想嘗試使用閉包。

button.click(function(){ 

    var myBtn = $(this); 
    $.postJson({ 
     data: myBtn.data(), 
     // blah 
    }); 

}); 

我不確定,但值得一試。

+0

「$ .postJson()scope」 - nope,在創建對象之前,將它傳遞給postJson – 2012-09-29 20:20:56

0

是不是變量'按鈕'您正在尋找數據()的選擇?使用buton.data()是因爲$(this)可以很容易地引用流程中的其他內容。

爲了進行調試,我建議您使用console.log(),例如,在嘗試發佈JSON之前,先做一個console.log($(this))並查看它所引用的內容。

相關問題