为什么我的jQuery + AJAX停止工作?

时间:2011-05-19 00:06:41

标签: javascript jquery ajax

我是JavaScript / jQuery / AJAX的新手,所以我怀疑这个问题是我看不到的错字。它工作正常,但在编辑过程中的某些时候,hide()+ show()方法停止工作(在Firefox + Chrome中测试)。我已经多次仔细研究过,看不出有什么问题。

的script.js

$(document).ready(function(){

    $('p').click(function() {
        $(this).hide();
    })

    $('#nav li a').click(function(){
        var toLoad = $(this).attr('href')+' #content';

        $('#content').hide('fast',loadContent);

        function loadContent() {
            $('#content').load(toLoad,'',showNewContent())
        }

        function showNewContent() {
                $('#content').show('normal');
        }
        return false;
    });
});

在我的 index.html 页面中,以下脚本包含在<head>部分中:

<script src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

2 个答案:

答案 0 :(得分:4)

您需要在<{1}} 之前添加jQuery

JavaScript代码同步执行。在您的示例中,script.js是(或至少应该是)$,当然undefined没有类似jQuery的方法。

此外,您的某个回调定义为undefined。最后的括号将调用该函数并将其结果作为回调传递回来,这在这种情况下不是您想要的。

相反,删除showNewContent()以仅传递对函数的引用。

答案 1 :(得分:0)

将index.html内容更改为

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="script.js"></script>

以及您在script.js中的代码:

$(document).ready(function(){

  $('p').click(function() {
    $(this).hide();
  })

  $('#nav li a').click(function(){
    var toLoad, loadContent, showNewContent; //keep the variable scope local
    toLoad = $(this).attr('href')+' #content';


    $('#content').hide('fast',loadContent);

    loadContent = function() {
        $('#content').load(toLoad,'',showNewContent)
    }

    showNewContent = function() {
            $('#content').show('normal');
    }
    return false;
  });
 });