开发者

jquery and javascript if...else problem

I've been trying to figure this one out for some time now, but no luck.

I use simplest jquery and ajax to load content into my page when navigation bar or sidebar links are clicked. I simply put this in document.ready:

$("#nav ul li a").click(function(){content_load($(this).attr('href'));return false;}); 

My content_load function is this:

function content_load(toLoad)
  {
  $('#content').hide('fast',loadContent);  
  function loadContent() 
    {  
    $('#content').load(toLoad,'',function(){showNewContent();tb_init('a.thickbox, area.thickbox, input.thickbox');});  
    }  
    function showNewContent()
      {  
      $('#content').show('fast');
      }  
   }

This works!

But...when I put simple if...else statement in function_load(), instead of simple ajax load, I get navigated to the page I wanted to load with load() function. It's like "return false" is ignored...

So this is the code that "breaks" everything:

function content_load(toLoad)
  {
  if(toLoad=="content/pag开发者_JAVA技巧e1.html") {//do something}
  else
    { 
    $('#content').hide('fast',loadContent);  
    function loadContent() 
      {  
      $('#content').load(toLoad,'',function(){showNewContent();tb_init('a.thickbox, area.thickbox, input.thickbox');});  
      }  
      function showNewContent()
        {  
        $('#content').show('fast');
        }  
     }
   }

Any idea why???

Thanks! Newman


Maybe it is a weird scope problem. Put the functions outside the if...else statement, or even better, use anonymous functions:

function content_load(toLoad) {
   if(toLoad=="content/page1.html") {
      //do something
   }
   else { 
      $('#content').hide('fast', function() {
         $(this).load(toLoad, function() {
             $(this).show('fast');
             tb_init('a.thickbox, area.thickbox, input.thickbox');
         });
      });
   }
}

That you are redirected to the page means that your function errors somewhere. If you have code where you have //do something, you should examine it too.

The error console of your browser should give you at least some information.


Instead of return false you can also call the appropriate methods of the event object:

$("#nav ul li a").click(function(event){
    // event.preventDefault();  <-- put here to always prevent reload, 
    //                              even on error (but should be avoided)
    content_load(this.href);
    event.preventDefault();
});


is it that your comment in first line commenting out the closing brace of your if statement


Don't know if that's a typo but the closing parentheses is commented out.

//do something}

That will cause it to break

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜