2013-03-26 141 views
0

我有一個用戶腳本,通過GM_xmlhttprequest觸發ajax調用,將帶有文本和鏈接的簡單頁面加載到名爲「debug」的div中。這工作得很好。現在我想要通過gm_xmlhttprequest請求所請求文檔中的每個鏈接。我不知道爲什麼我的功能無法正常工作來自ajax請求的鏈接不通過ajax請求

$('.ajax, .ajaxn').click(function(event) { 
event.preventDefault(); 
var href = $(this).attr('href'); 
GM_xmlhttpRequest({ 
       method: "GET", 
       url: href, 
       headers: { 
        "Content-Type": "application/x-www-form-urlencoded" 
        }, 
         onload: function(response) { 
           $('#debug').html(''); 
           $('#debug').append(response.responseText).fadeIn(5000); 
             } 
      }); 
}); 

響應中的鏈接有類ajaxn,和螢火蟲的DOM/HTML面板顯示的響應實際上是插入#調試

任何提示?

+0

你說「響應實際上被插入#debug」。那麼有什麼不工作? – wimh 2013-03-26 11:11:33

+0

我認爲你通過調用'$('#debug')。html('');'來移除所有以前的內容。嘗試一下'console.log'來確定是否所有的xmlHttpRequests都被執行了? – Laoujin 2013-03-26 12:44:12

回答

2

的問題是不明確的,但假設你想要的click處理火災,如果一個鏈接被點擊的#debug內容(而不是自動加載鏈接或???)...

然後唐不使用.click()方法。使用jQuery's .on() method這會觸發當前,和任何未來,與選擇器匹配的節點。

的代碼變成這樣的:

$(document).on ("click", ".ajax, .ajaxn", function (event) { 
    event.preventDefault(); 
    var href = $(this).attr('href'); 

    GM_xmlhttpRequest ({ 
     method:  "GET", 
     url:  href, 
     headers: { 
      "Content-Type": "application/x-www-form-urlencoded" 
     }, 
     onload:  function (response) { 
      $('#debug').empty(); 
      $('#debug').append (response.responseText).fadeIn (5000); 
     } 
    }); 
}); 


另外,不要使用$('#debug').html('');使用$('#debug').empty();代替。這將會更快,並且代碼更加自我記錄。

+0

+1,儘管使用'$('#debug')。on(「click」,「.ajax,.ajaxn」,function ...「會稍微高效一些,所以偵聽器只會觸發'debug' div。 – 2013-03-27 09:19:37

+0

@IanRoberts,是的,它會更有效率,除非不清楚* .ajax或'.ajaxn'節點是否在'#debug'元素中,所以我播放它安全。 – 2013-03-27 10:24:28