Loading... # html中引入外部html的方法 ## 一、直接用js调用 > 方法:$("#page1").load("page/Page_1.html"); **index.html Demo** ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script> </head> <body> <div id="page1"></div> <div id="page2"></div> <script> $("#page1").load("./page/Page_1.html"); $("#page2").load("./page/Page_2.html"); </script> </body> </html> ``` **Page_1.html Demo** ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div style="border:1px solid red; width: 98%; height: 65px; position: absolute; top: 5px;">这是顶部</div> </body> </html> ``` **Page_2.html Demo** ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div style="border:5px solid red; width: 98%; height: 65px; position: absolute; bottom: 0px;">这是底部</div> </body> </html> ``` 如你是直接浏览器打开 html 文件,那么可能会出现跨域的情况 ``` Access to XMLHttpRequest at 'file:///C:/Users/dengw/Desktop/page/page/Page_1.html' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https. ``` 禁止跨域是浏览器的安全限制机制,但是可以通过设置来绕过这个限制(如果经常 完前端代码 建议在本机装个web容器。。。),常见的方式是 右击chrome快捷方式,选择“属性”,在“快捷方式”下的“目标”中添加 `--allow-file-access-from-files` (最前面有个空格),重启chrome即可如下: ``` C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files //注意有空格,关闭浏览器然后重启浏览器即可支持 ``` Jquery的load()一般是加载服务器上的文件(非本地文件),这个概念需要弄清楚。要发布网站后通过http协议进行访问,本地file协议浏览会产生跨域问题。 除非是静态文件html调用load,但是这个也是有的浏览器支持(firefox和chrome),有的不支持。 End Thanks!😁 最后修改:2021 年 01 月 13 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 0 如果觉得我的文章对你有用,请随意赞赏