2012-10-17 39 views
1

我產生具有唯一ID的動態CSS按鈕,我用下面單擊處理動態按鈕和on.click事件問題

$(document.body).on('click', 'a', function() { 
    if (typeof(this.id) != "undefined") { //check if id exists 
     var n = this.id.split("%"); 
     if (n[0] == "jsonpbtn") { //check if one of our buttons  
      var surl = "http://www.blah.com/tree/jsonp/foo/" + n[1]; 
      $.ajax({ 
       url: surl, 
       cache: false, 
       dataType: "jsonp", 
       jsonp: false, 
       jsonpCallback: 'foo', 
       error: function(XHR, textStatus, errorThrown) { 
        alert(textStatus + ":" + errorThrown) 
       }, 
       success: function(foo) { 
        $('#blah' + foo.id).html(foo.message); 
       } 
      }); 
     } 
    } 
});​ 

捕獲點擊事件雖然Ajax調用對頁面生成錯誤「parsererror:錯誤:foo未被調用」;我相信問題是這個循環遍歷頁面上的所有「a」元素,並且 爲每個「jsonpbtn」調用函數?

+0

問題在於'http://www.blah.com/tree/jsonp/foo/n [1]'沒有返回名爲'foo'的JSONP函數。響應應該看起來像'foo({「foo」:「bar」}) –

+0

同意Kevin B.它在服務器端,它只是格式不正確JSONP,_foo沒有被調用_當沒有'foo(JSON )' – davidkonrad

+0

正如所述的ajax調用的作品,如果我只有一個按鈕在頁面上沒有錯誤。 –

回答

0

我發現,通過在ajax調用之前插入一個初步階段,在該階段我更改按鈕狀態可以修復問題。

$(document.body).on('click', 'a', function() { 
if (typeof(this.id) != "undefined") { //check if id exists 
    var n = this.id.split("%"); 
    if (n[0] == "jsonpbtn") { //check if one of our buttons  
     var surl = "http://www.blah.com/tree/jsonp/foo/" + n[1]; 
     $('#div_id'+n[1]).html('<a class="button" href="#">working</a>');//<-added this 
     $.ajax({ 
      url: surl, 
      cache: false, 
      dataType: "jsonp", 
      jsonp: false, 
      jsonpCallback: 'foo', 
      error: function(XHR, textStatus, errorThrown) { 
       alert(textStatus + ":" + errorThrown) 
      }, 
      success: function(foo) { 
       $('#blah' + foo.id).html(foo.message); 
      } 
     }); 
    } 
} 
});​ 

感謝那些試圖幫助的人。 Registers Martin Martin