jquery load()没有加载内容

jquery load() is not loading the content

本文关键字:加载 load jquery      更新时间:2023-09-26

我有一个带有超链接的页面,当单击它时,我希望它从另一个文件加载内容,这样页面就不必刷新了。当前".contain"的内容应替换为外部html文件中".contation"的内容。

这是我的html

 <li> <a href="#" class="loader" id="indexLink">Chris Lebeau</a>

这是我在页面底部的jQuery。

  <script type="text/javascript">
     jQuery(document).ready(function() {
     jQuery("#indexLink").click(function(event) {
     jQuery("div.container").html(ajax_load).load("index.html");
    event.preventDefault();
});

});

当你点击ORG图表中的第一个人时@http://frommesetc.com/test/org.htmlcontainer应该淡出,而index.html中的.contain应该淡出。

您的代码中缺少一个javascript:位:

<a href="javascript:load()">Chris Lebeau</a>

编辑

您还需要定义load()函数:

<script type="text/javascript">
...
var loadUrl = "/index.html";
function load() {
    $("div.container").html(ajax_load).load(loadUrl);
}
</script>

这假设您在具有class="container"的页面上有一些HTML元素。

编辑2

最后,建议现在使用Unobtrusive JavaScript几天。要使用这种方法,请执行以下操作:

<a href="index.html" id="chris_lebeau">Chris Lebeau</a>
<script type="text/javascript">
jQuery(document).ready(function() {
    jQuery("#chris_lebeau").click(function(event) {
        jQuery("div.container").html(ajax_load).load("index.html");
        event.preventDefault();
    });
});
</script>

这是目前"最好"的方法,但如果javascript:load()方法有效,那就足够了。

这里有几个问题。

首先,您没有类"container"的元素,因此您的单击处理程序实际上什么也没做。

此外,如果您有一个用于点击的监听器,那么就不需要从锚点链接到JS函数。

这里有一个例子:

HTML:
<a class="button" href="#">Hello</a>
<div class="newcontent"></div>
JAVASCRIPT:
var loadingAnim = "<img src='img/ajax-loader.gif' alt='loading...' />";
var dataToLoad = "/index.html";
$("a.button").click(function(){
    $("div.newcontent")
        .html(loadingAnim)
        .load(dataToLoad);
});

使用

jQuery("div.container").load("index.html");