views:

26

answers:

2

I'm trying to build a webpage which contains some tabs, by clicking on a tab, it will use AJAX to load content below the tabs.

The problem: In older versions of Internet Explorer clicking on a tab will result in getting redirected to the tab link, instead of loading the content behind that link via AJAX.

My html code:

<ul id="nav">
  <li><a href="page_1.html">Page 1</a></li>
  <li><a href="page_2.html">Page 2</a></li>
  <li><a href="page_3.html">Page 3</a></li>
</ul>

<div id="ajax-content">This is default text, which will be replaced</div>

My Jquery code:

$(document).ready(function() {
    $("#nav li a").click(function() {

        $("#ajax-content").empty().append("<div id='loading'><img src='images/loading.gif' alt='Loading' /></div>");
        $("#nav li a").removeClass('current');
        $(this).addClass('current');

        $.ajax({
            url: this.href,
            success: function(html) {
                $("#ajax-content").empty().append(html);
            }
        });
        return false;
    });
});
A: 

I believe that adding event.stopPropagation() in the end of the click handler (you also need to reference event as a handler argument: $("#nav li a").click(function(event) {...});) will do the trick.

David Parunakian
No, the `return false` at the end of the click handler does that anyway. (It was hard to tell it was there because his indentation was messed up, but it was there.)
T.J. Crowder
+1  A: 

As you know, the return false; at the end of the click handler should both stop bubbling and prevent the default action. But of course, if you never get there, then the default will continue.

So the question has to be: Have you walked through the code with a debugger to see whether it's throwing an error and/or that everything that should be matched by your selectors is being matched? My guess is that something in the click handler is failing on IE for some reason and so your return false isn't happening, or (of course) that the click handler isn't getting triggered at all. Over the years there have been several debuggers for scripts on IE, most recently the free Visual Studio Express.

One particularly rich area for finding bugs that only happen on IE is in its namespacing issues, particularly since you say this happens on "older" versions of IE. Details in this blog post, but basically all the way through IE7 IE mashes together several namespaces that should be completely distinct (for instance, it treats all id and name values as being in the same namespace, so if you have an element with name="foo" and another element with id="foo", IE will get confused). This mashed-together namespace will affect your jQuery selectors, since jQuery selectors that use IDs eventually use the built-in document.getElementById, and IE (6 and 7) uses the mashed-up namespace with that function.

T.J. Crowder