jQuery.load加载HTML文件 [英] jQuery.load to load HTML file

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

问题描述

在此之前,我从未使用过 jQuery ,但是我会解释我要做什么.

I've never used jQuery before this, but I'll explain what I'm trying to do.

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>My Awesome Website</title>
        <link href="style.css" rel="stylesheet" type="text/css"/>
        <link rel="shortcut icon" href="/favicon.ico" />
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>

<!--    <iframe width="100%" height="175" frameborder="0" scrolling="no" src="navbar.html"></iframe> I used to use this - but i cant have dropdown menus. -->
            <!-- This is my problem -->
        <script>
                $('#navbar').load('./navbar.html');
        </script>
        <noscript>
            <h1>Please enable Javascript!</h1>
        </noscript>

        <div id="container">
                <!-- Content Here -->
        </div>

    </body>
</html>

navbar.html

<div id="navbar">
        <li><object width="64" height="64" data="favicon.svg" type="image/svg+xml"></object></li>
        <li><object width="64" height="64" data="icons/tech.svg" type="image/svg+xml"></object></li>
        <li><object width="64" height="64" data="icons/games.svg" type="image/svg+xml"></object></li>
        <li><object width="64" height="64" data="icons/contact.svg" type="image/svg+xml"></object></li>
</div>

因此,我要在此处执行的操作是拥有许多HTML页面,这些页面都将所有 link 链接到一个navbar html页面,因此,当我更改navbar.html时,不必更改每个页面

So what I'm trying to do here, is have many HTML pages which all link to one navbar html page, so when I change the navbar.html, I dont have to change every page.

我已经在此处提出了另一个问题. Davor Milnaric 建议如果使用的是jquery,则可以尝试使用'.load()'函数.api. jquery.com/load",但无法正常工作.我究竟做错了什么?我如何解决它?任何帮助将不胜感激.

I already have another question here. Davor Milnaric suggested "if you are using jquery, you can try with '.load()' function. api.jquery.com/load" but I can't get it to work. What am I doing wrong? How do I fix it? Any help would be much appreciated.

推荐答案

您需要做两件事:

  1. 使用$(document).ready()-在此处中阅读;所有jQuery代码都必须像这样包装:

  1. Use $(document).ready() - read here; All jQuery code must be wrapped like this:

$(document).ready(function(){

    //jquery code goes here....        

});

  • 更改

  • Change

    $('#navbar').load('./navbar.html');

    $('#container').load('./navbar.html');
    

    ..您没有id ="navbar"的元素 并根据:

    .. you don't have an element with id="navbar" and according to this:

    如果选择器没有匹配任何元素(在这种情况下,如果文档不包含id ="result"的元素(在本例中为"navbar" ),则Ajax请求将不发送.

    If no element is matched by the selector — in this case, if the document does not contain an element with id="result" (in our case "navbar") — the Ajax request will not be sent.

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

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