【问题标题】:jQuery - Reload head scripts after a jQuery.get functionjQuery - 在 jQuery.get 函数之后重新加载头脚本
【发布时间】:2017-06-27 15:56:29
【问题描述】:

我已经编写了这段代码来切换我的 html 内容:

$.get( "header.html", function( data ) {
  $( "#header-import" ).html( data );
  alert( "Load was performed." );
});
$.get( "navigation.html", function( data ) {
  $( "#navigation-import" ).html( data );
  alert( "Load was performed." );
});
$.get( "home.html", function( data ) {
  $( "#content-import" ).html( data );
  alert( "Load was performed." );
});

我导入的 JS 脚本似乎没有正确加载。 我想我必须在页面加载后“重新加载”我的主 html 文件中的部分。有什么想法吗?我尝试了一些东西,但没有成功。

【问题讨论】:

    标签: javascript jquery html import get


    【解决方案1】:

    使用 .ajax() 并拥有一个 dataType,会产生一个完美的工作最终结果:

    <html>
        <head>
    
        <script src="jquery-1.10.2.js"></script>
    
        <script type="text/javascript">
            jQuery(document).ready(function(){
    
    
                jQuery.ajax({
                    url : "test1.html",
                    dataType: "html",
                    success : function (data) {
                        jQuery( "#header" ).html( data );
                        console.log("a: "+data);
                        //alert( "Load was performed." );
                    }
                });
    
                jQuery.ajax({
                    url : "test2.html",
                    dataType: "html",
                    success : function (data) {
                        jQuery( "#navigation" ).html( data );
                        console.log("b: "+data);
                        //alert( "Load was performed." );
                    }
                });
    
    
    
            });
        </script>
        </head>
        <body>
    
            <h1>TEST</h1>
            <div id="header">
    
            </div>
    
            <div id="navigation">
    
            </div>
        </body>
    </html>
    

    【讨论】:

    • 它工作正常,谢谢,你知道我如何调用函数onclick吗?
    • 太棒了!是的...您将两个jQuery.ajax() 调用封装在:jQuery("SELECTOR").on( 'click', function () { //jQuery.ajax() calls }); 其中SELECTOR 是一个类或一个ID(如果它是一个类,它将是.classname 如果它是ID,它将是@ 987654327@
    • 工作得很好,你知道如何在加载内容时在头部添加内容吗:f.ex.: $.ajax({ url : "home.html", dataType: "html" , 成功 : function (data) { jQuery( "#content-import" ).html( data ); }});有了这个,它应该在 部分导入:“
    • 很高兴听到这个消息;至于您的后续问题:为什么不首先将该库包含在&lt;head&gt; 中?如果它是 ONLY 一个文件的一部分,则将 lib 包含在该文件的 &lt;head&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多