开发者

Why has my jQuery + AJAX stopped working?

I'm fairly new to JavaScript/jQuery/AJAX, so I suspect the issue is some typo I'm not seeing. It was working fine, but at some point during editing the hide() + show() methods stopped working (tested it in Firefox + Chrome). I've pored over it many times and can't see what's wrong.

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;
    });
});

In my index.html page the following script includes a开发者_开发百科re in the <head> section:

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


You need to include jQuery before your script.js.

JavaScript code is executed synchronously. In your example, $ is (or at least should be) undefined, and of course undefined has no jQuery like methods.

Also, one of your callbacks is defined as showNewContent(). The parenthesis at the end will call that function and pass its results back as the callback, which is not what you want in this circumstance.

Instead, drop the () to pass just the reference to the function.


Change your index.html stuff to

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

and your code in script.js to:

$(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;
  });
 });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜