【问题标题】:Debugging jQuery load() for links in content replaced by load()为由 load() 替换的内容中的链接调试 jQuery load()
【发布时间】:2013-10-29 17:49:53
【问题描述】:

在我的 main.js 中,我有两个与链接相关的规则。应该处理所有不以 http://、mailto: 或 # 开头的链接。它使用 load() 替换 $('#contentMain') 中的内容。另一个处理以 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");

问题似乎是 /contact 之类的链接不会触发第一条规则 IF 它们在 $('#contentMain') 之后 load() 替换了第一条内容他们被点击的时间。如果您在加载/content 时单击#contentMain 内的/contact,则遵守规则,您会看到console.log() 等。

那么为什么用 load() 替换的内容不遵守 main.js 中的规则?这些规则目前在 $(document).ready(function(){ 中,但我也尝试将其删除以查看是否有帮助。

【问题讨论】:

  • 不要将它们视为规则,将它们视为属性。您将属性赋予原始属性,但新属性没有这些属性。您要么必须使用事件委托,要么在添加新元素时重新绑定这些事件。
  • 谢谢@KevinB!谷歌了一下,发现jqueryfordesigners.com/simple-use-of-event-delegation

标签: javascript jquery html jquery-load


【解决方案1】:

您可以使用.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;   
}});

【讨论】:

    【解决方案2】:

    根据@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;   
        }
    });
    

    【讨论】:

    • .delegate() 已被 .on() 取代,您应该从 jQuery 1.7 开始使用它。
    猜你喜欢
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 2013-09-09
    相关资源
    最近更新 更多