【问题标题】:jQuery.load to load HTML filejQuery.load 加载 HTML 文件
【发布时间】:2013-05-21 06:18:00
【问题描述】:

在此之前我从未使用过jQuery,但我会解释我想要做什么。

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>My Awesome Website</title>
        <link href="style.css" rel="stylesheet" type="text/css"/>
        <link rel="shortcut icon" href="/favicon.ico" />
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>

<!--    <iframe width="100%" height="175" frameborder="0" scrolling="no" src="navbar.html"></iframe> I used to use this - but i cant have dropdown menus. -->
            <!-- This is my problem -->
        <script>
                $('#navbar').load('./navbar.html');
        </script>
        <noscript>
            <h1>Please enable Javascript!</h1>
        </noscript>

        <div id="container">
                <!-- Content Here -->
        </div>

    </body>
</html>

navbar.html

<div id="navbar">
        <li><object width="64" height="64" data="favicon.svg" type="image/svg+xml"></object></li>
        <li><object width="64" height="64" data="icons/tech.svg" type="image/svg+xml"></object></li>
        <li><object width="64" height="64" data="icons/games.svg" type="image/svg+xml"></object></li>
        <li><object width="64" height="64" data="icons/contact.svg" type="image/svg+xml"></object></li>
</div>

所以我在这里尝试做的是有许多 HTML 页面,它们都 链接 到一个导航栏 html 页面,所以当我更改 navbar.html 时,我不必更改每一页.

我已经有另一个问题hereDavor Milnaric 建议“如果你使用 jquery,你可以尝试使用 '.load()' 函数。api.jquery.com/load”但我无法让它工作。我究竟做错了什么?我如何解决它?任何帮助将不胜感激。

【问题讨论】:

    标签: jquery html web navbar


    【解决方案1】:

    您也可能需要等待 DOM 加载。

        <script>
            $(document).ready(function() {
                $('#result').load('navbar.html #navbar', function() {
                    alert("loaded");
                });
            });
        </script>
    
        <div id="result">
        </div>
    

    【讨论】:

    • 您好,感谢您的回复。 :) 当我尝试这个时,没有任何改变,导航栏仍然没有加载......有什么想法吗?
    • 如果你在浏览器打开dev tools,你会看到错误,可能是'跨源请求只支持协议方案:http、data...'
    【解决方案2】:

    你需要做两件事:

    1. 使用 $(document).ready() - 阅读 here;所有 jQuery 代码都必须像这样包装:

      $(document).ready(function(){
      
          //jquery code goes here....        
      
      });
      
    2. 改变

      $('#navbar').load('./navbar.html');

    $('#container').load('./navbar.html');
    

    .. 你没有 id="navbar" 的元素 并根据this

    如果选择器没有匹配任何元素——在这种情况下,如果文档不包含 id="result" 的元素(在我们的例子中是“navbar”)——Ajax 请求将不发送。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多