2017-02-10 125 views
0

我想加載一個html文件(home.html)的內容到位於主html文件(index.html)內的div容器中,點擊一個鏈接後,我想用jquery/ajax來做到這一點。我試圖找到答案,但只有遇到有關PHP的答案,而不是HTML。如何使用jQuery/AJAX加載HTML div內的html頁面內容?

這是HTML代碼,我到目前爲止有:

<!-- navigation bar --> 
    <nav> 
    <ul> 
     <li><a href="#" data-target="home.html">HOME</a></li> 
     <li><a href="#" data-target="work.html">MY WORK</a></li> 
     <li><a href="#" data-target="about.html">ABOUT ME</a></li> 
     <li><a href="#" data-target="services.html">SERVICES</a></li> 
     <li><a href="#" data-target="contact.html">CONTACT ME</a></li> 
    </ul> 
    </nav> 

    <!-- content div --> 

    <div id="content"> 

    </div> 

    <!-- footer --> 
    <section> 
    </section> 
    <footer> 
    <p>Copyright &copy; 2017, All Rights Reserved</p> 
    </footer> 
</div> 
+0

可能重複[如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-打電話) –

+0

我來看看吧,謝謝! :) – Lizz

+1

http://api.jquery.com/load/ –

回答

1

你可以嘗試以下;在這裏你得到load.html的內容,並將其放入content div。

<!-- navigation bar --> 
      <nav> 
      <ul> 
       <li><a href="#" data-target="home.html">HOME</a></li> 
       <li><a href="#" data-target="work.html">MY WORK</a></li> 
       <li><a href="#" data-target="about.html">ABOUT ME</a></li> 
       <li><a href="#" data-target="services.html">SERVICES</a></li> 
       <li><a href="#" data-target="contact.html">CONTACT ME</a></li> 
      </ul> 
      </nav> 

      <!-- content div --> 

      <div id="content"> 

      </div> 

      <!-- footer --> 
      <section> 
      </section> 
      <footer> 
      <p>Copyright &copy; 2017, All Rights Reserved</p> 
      </footer> 
     </div> 

<script> 
$("#content").load("/resources/load.html"); 
</script> 
0

jQuery代碼看起來是這樣的:

$('a').each(function(b,c){  //loop through each a element 
    $(c).on('click',function(){ //add click event listener 
     var link = $(this).attr('data-target'); //get the link from attribute 
     $('#content').load(link); //load the link's content into container 
    }); 
}); 

它將通過所有a元素循環和data-target屬性獲取鏈接。只要記住添加jQuery到您的網頁。

相關問題