2013-03-26 138 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