简体   繁体   English

如何使所有链接动态加载页面? (甚至是动态加载页面中的链接)

[英]How can I make ALL links load pages dynamically? (Even links in dynamically loaded pages)

So I have a script like this 所以我有一个像这样的脚本

    <script type="text/javascript"
            src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
    </script>
    <script type="text/javascript">
       $(document).ready(function(){
       $("a[href*='http://']:not([href*='"+location.hostname+"'])").attr("target","_blank");

       $("a[target!='_blank'][target!='_top']").click(function(){

       var url=$(this).attr("href")+'?jquery=1';
       ajaxpage(url,'actualcontent');

       window.location.hash=$(this).attr("href");
        return false;
    });


});
    </script>

and it works great. 而且效果很好。 It means all my links load dynamically within the DIV - awesome. 这意味着我所有的链接都在DIV中动态加载-非常棒。 But, the links loaded in those div, don't load dynamically when clicked. 但是,这些div中加载的链接在单击时不会动态加载。 and if I include this script in it, it still doesn't work. 如果我在其中包含此脚本,它仍然无法正常工作。 And on a similar note, is there a way of making javascript in pages, which have been loaded dynamically, work? 同样,是否有一种方法可以使已动态加载的页面中的javascript工作? Without including it in the original header? 没有在原始标题中包含它?

Thanks. 谢谢。

Disclaimer: To use this solution, you'll need to upgrade to jQuery 1.3 or jQuery 1.4+ 免责声明: 要使用此解决方案,您需要升级到jQuery 1.3或jQuery 1.4+
(But you should, there are many performance improvements and bug fixes since 1.2.6) (但您应该自1.2.6起进行了许多性能改进和错误修复)


Instead of .click() you can use .live() here, like this: 代替.click()您可以在此处使用.live() ,如下所示:

$("a[target!='_blank'][target!='_top']").live('click', function(){

.live() works on dynamically added elements as well, since it's listening for the bubbling click event at document , rather than being a handler on the element itself. .live()可用于动态添加的元素,因为它正在侦听document冒泡的click事件,而不是作为元素本身的处理程序。

Not sure what your problem is. 不知道您的问题是什么。 You are saying that the links that are added after this function rn do not use this function? 您是说在此功能之后添加的链接不使用该功能? hint, you need to rescan the page to update the links in that div OR you can avoid that and use live() . 提示,您需要重新扫描页面以更新该div中的链接,或者可以避免使用live()

Use .delegate() 使用.delegate()

// Don't need to put this in a $(document).ready() callback.
$(document).delegate("a[target!='_blank'][target!='_top']", "click", function(e){
    var url=$(this).attr("href")+'?jquery=1';
    ajaxpage(url,'actualcontent');
    window.location.hash=$(this).attr("href");
    e.preventDefault();
    return false;
});

$(document).delegate("a[href*='http://']:not([href*='"+location.hostname+"'])", "click", function(){
    // lazy attr setting, reduces query cost
    $(this).attr("target", "_blank")
});

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

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