2013-05-26 60 views
1

我已经从来没有在此之前使用jQuery,但我会解释我正在尝试做什么。jQuery.load加载HTML文件

的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页面,所有链接一个navbar html页面,所以当我更改navbar.html时,我不必更改每个页面。

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

回答

6

你需要做两件事情:

  1. 使用$(文件)。就绪() - 读here;所有jQuery代码必须包装这样的:

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

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

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

..你没有与ID元素= “navbar” 并根据this

如果没有元件被选择匹配的 - 在这种情况下,如果文档不包含具有ID =“结果”的元件(在我们的情况下,“导航栏”) - Ajax请求将不发送。

2

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

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

    <div id="result"> 
    </div> 
+0

嗨,谢谢你的回复。 :)当我尝试这个,没有改变,导航栏仍然不加载...任何想法? – Yharooer