質問

In my main.js I have two link related rules. One should handle all links that do not start with http://, mailto:, or #. It uses load() to replace content in $('#contentMain'). The other handles links that do start with http:// and opens them in a new tab.

$("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. If you click /contact inside #contentMain while /content is loaded then the rule is obeyed, you see the console.log() etc.

So why would content replaced by load() not obey rules in main.js? Those rules are currently inside of a $(document).ready(function(){ but I also tried removing it to see if it helped.

役に立ちましたか?

解決

You can use .on() handler, like this:

$("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

$("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帰属
所属していません StackOverflow
scroll top