簡體   English   中英

使用 jquery 在 div 標簽中動態加載 html 頁面

[英]load html page in div tag using jquery dynamically

使用 JavaScript 或 jQuery 在 div 標簽內動態加載 html 頁面。

 <html> <head> <title>Untitled Document</title> </head> <script type="text/javascript"> $(document).ready(function(){ $('#btn').click(function(){ $('#div_content').html('C:/xampp/htdocs/ex1.html'); }); }); </script> <body> <input type="button" id="btn" value="Load" /> <div id="d_content"> </div> </body> </html>

但它不起作用..

您遇到的問題是 javascript 將page.html視為 object,訪問屬性html 您需要做的是引用string,因此它按照預期的方式處理.. 作為 string:

 $('#div_content').load('page.html');

更新1:

首先,您上面的內容稱為jQuery jQuery 是一個 javascript 庫,在使用 jquery 對象的任何方法之前,您必須將其包含在 head 標簽中:

 <script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>

您必須在文檔頭中包含上述行,才能訪問 jQuery $ object 的方法和屬性。

您目前沒有這樣做的事實是您的代碼被破壞並拒絕工作的原因。 此外,根據您的設置,您可能希望自己提供 jquery 文件,在這種情況下,您可以下載它並將其放在服務器上的某個位置。

其次, C:\不是您的 web 根。 localhost是,所以要讓那個位工作你必須使用'ex1.html'的url。 而已。 由於您的文檔已經在 web 根目錄中(或者至少我認為是),它應該可以訪問任何相鄰文件......否則..

假設您的索引文件在 htdocs 中。 您的索引的 url 將是localhost/index.ext (其中 ext 是您使用的任何文件擴展名)。 然后ex1.html位於不同的文件夾中,例如“文件夾 1”。 要在您的 jquery 代碼中正確訪問它.. folder1/ex1.html

最后,腳本標簽 go 在頭部或身體中.. 兩者都不是。

$(document).ready(function(){ $('#btn').click(function(){ $('#div_content').load('html.page'); }); });
$('#div_content').load("page.html");

嘗試這個:

 $(document).ready(function(){ $('#btn').click(function(){ $.get('page.html').success(function(data) { $('#div_content').html(data); }); }); });

page.html替換為您的頁面

Try this..

$(document).ready(function(){
    $('#btn').click(function(){   
       $('#div_content').html('page.html');
    });
});

main.html

 <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <title>Untitled Document</title> </head> <script> function check(){ $('#tar').load('test.html #target'); // here 'test.html' is a page and 'target' id a id of 'test.html' } </script> <body> <input type="button" id="btn" value="Go" onclick="check();"/> <div id="tar"> </div> </body> </html>

測試.html

 <html> <head></head> <body> <div id='target'> I am from test page. </div> </body> </html>

在這里我寫了 2 個 html 程序。 該問題僅發生在 function 上。 我糾正了這一點,現在它工作得很好。 我們也可以加載 txt 文件:示例:

 function check(){ $('#tar').load('test.txt'); // here 'test.txt' is a text file } </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM