简体   繁体   English

调试jQuery load()以查找由load()替换的内容中的链接

[英]Debugging jQuery load() for links in content replaced by load()

In my main.js I have two link related rules. 在我的main.js中,我有两个与链接有关的规则。 One should handle all links that do not start with http://, mailto:, or #. 应该处理所有不以http://,mailto:或#开头的链接。 It uses load() to replace content in $('#contentMain'). 它使用load()替换$('#contentMain')中的内容。 The other handles links that do start with http:// and opens them in a new tab. 另一个处理以http://开头的链接,并在新选项卡中打开它们。

$("a:not([href^='http://'],[href^='#'],[href^='mailto:'])").click( function(e) { 
    console.log('Caught click, loading via AJAX');
    var url = $(this).attr("href");
    var title = ($(this).attr("title")) ? ': ' + $(this).attr("title") : '';
    e.preventDefault(); 
    if(url!=window.location){
       window.history.pushState({path:url},title,url);
       $('#contentMain').load(url);
        document.title = "It's New Orleans" + title;   
    }
});

$("a[href^='http://']").attr("target","_blank");

The problem seems to be that links like /contact do not trigger the first rule IF they are inside $('#contentMain') after load() has replaced content on the first time they are clicked . 问题似乎是, 在首次单击 load()替换内容之后, 如果 / contact之类的链接不会触发第一条规则, 前提是它们位于$('#contentMain')内部。 If you click /contact inside #contentMain while /content is loaded then the rule is obeyed, you see the console.log() etc. 如果在加载/ content时单击#contentMain内的/ contact,则该规则得到遵守,您会看到console.log()等。

So why would content replaced by load() not obey rules in main.js? 那么,为什么要用load()替换的内容不遵守main.js中的规则? Those rules are currently inside of a $(document).ready(function(){ but I also tried removing it to see if it helped. 这些规则当前位于$(document).ready(function(){内部,但我也尝试将其删除以查看是否有帮助。

You can use .on() handler, like this: 您可以使用.on()处理程序,如下所示:

$("body" ).on( "click", "a:not([href^='http://'],[href^='#'],[href^='mailto:'])",function(e) { 
console.log('Caught click, loading via AJAX');
var url = $(this).attr("href");
var title = ($(this).attr("title")) ? ': ' + $(this).attr("title") : '';
e.preventDefault(); 
if(url!=window.location){
   window.history.pushState({path:url},title,url);
   $('#contentMain').load(url);
    document.title = "It's New Orleans" + title;   
}});

Per @KevinB's comment the answer is replacing with 根据@KevinB的评论,答案将替换为

$("body").delegate("a:not([href^='http://'],[href^='#'],[href^='mailto:'])", "click", function(e) { 
    console.log('Caught click, loading via AJAX');
    var url = $(this).attr("href");
    var title = ($(this).attr("title")) ? ': ' + $(this).attr("title") : '';
    e.preventDefault(); 
    if(url!=window.location){
       window.history.pushState({path:url},title,url);
       $('#contentMain').load(url);
        document.title = "It's New Orleans" + title;   
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM