如何使用jQuery包含HTML文件? [英] How to include an HTML file with jQuery?

查看:87
本文介绍了如何使用jQuery包含HTML文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的代码分开,所以我决定将每个 div 分割为html文件。每个HTML文件都有一些jQuery点击事件。我有两个文件 index.html menu.html



问题是我必须在两个文件中包含jQuery库才能使它工作。



有没有什么办法可以包含库一次并拥有它在两个文件上工作?我试图将库仅包含在索引页中,但是然后菜单单击不起作用。



我通过iframe包含了 menu.html 文件。

 < iframe src =left-menu.html>< / iframe> 


解决方案

您可以添加菜单。 html 加入到 index.html 与jQuery的 load() 方法。这样,在 index.html 中创建的jQuery实例也适用于从 menu.html 加载的内容。



例如在 index.html 中可以这样做:

<$ (); $($'code> $(document).ready(function(){
$('#some-menu')。load('some-local-path / menu.html');
});

请注意 $('#some-menu') index.html 中的另一个元素,我们在其中加载 menu.html 的内容。同样重要的是要注意,由于同源策略,作为 load()方法的一部分执行的AJAX请求只适用于相同域,协议和端口中的文件(除非您使用 CORS )。


I want to make my code separate so I decided to divide each div to html files. Each HTML file has some jQuery click events. I have 2 files index.html and menu.html.

Problem is that I have to include the jQuery library in both files to make it work.

Is there any way that I can include library one time and have it work on both files? I tried to include the library in the index page only, but then the menu click doesn't work.

I included the menu.html file through an iframe.

<iframe src="left-menu.html"></iframe>

解决方案

You can add menu.html into the DOM of index.html with the jQuery load() method. This way the jQuery instance created in index.html would also apply to the content loaded from menu.html.

For example in index.html you can do:

$(document).ready(function() {
    $('#some-menu').load('some-local-path/menu.html');
});

Note how $('#some-menu') is just another element in index.html into which we load the contents of menu.html. It's also important to note that because of the same-origin-policy, the AJAX request performed as part of the load() method would only work with files in the same domain, protocol and port (unless you're using CORS).

这篇关于如何使用jQuery包含HTML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆