jQuery动态加载本地文件 [英] JQuery load local files dynamically

查看:242
本文介绍了jQuery动态加载本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发HTML原型,页面中的所有静态内容都保存在不同的文件中.我想使用这些文件作为HTML原型中的文件. 以下是用于调用两个HTML包含文件的HTML代码.

I am developing a HTML prototype, all the static content in the page is saved in different files. I want to use these files as includes in my HTML prototype. Below is HTML code for calling the two HTML include files.

<div class="include-file" file="header.html"></div>
<div class="include-file" file="footer.html"></div>

我正在使用jquery load()方法来包含这些文件.

I am using jquery load() method to include these files.

$(function () {
    var fileName = $(".include-file").attr('file');
     $(".include-file").load(fileName);
});

当我在页面中仅包含一个文件时,此功能可以正常工作.

This function works fine when i am including only one file in a page.

问题:

1.当我包含两个文件时,第二个文件(footer.html)不加载,第一个文件(header.html)加载两次.

1.When I include two files the second file(footer.html) doesn't load,and first file(header.html)loads twice.

2.单个文件加载可以在FF,IE9中运行,但不能在Chrome浏览器中运行.(注意:所有文件都是本地文件,我不打算使用网络服务器,因为这只是一个原型)

2.Single file loading works in FF,IE9 but doesn't work in Chrome.(Note: All files are local, I am not planning to use a web server, as this is just a prototype)

推荐答案

您在每个.load上使用相同的文件名.尝试以下类似的方法,

You are using same filename on each .load. Try something like below,

$(function () {
    $(".include-file").each (function () {
       $(this).load($(this).attr('file'));
     });
});

这应该可以解决您的第一个问题.

This should fix your first problem.

尝试为您规避同源政策的方法第二个问题.

这篇关于jQuery动态加载本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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