简体   繁体   中英

jQuery .load() of HTML file not consistently working in Chrome

I know my question is sort of a duplicate of numerous others, but I have yet to find an answer that solves my issue. I'm trying to use a responsive menu on several pages, so I've placed the HTML code for it in a separate file... minus the HTML, HEAD, BODY tags. Let's call that menu.html. The menu needs CSS and JS files, which I reference in index.html. The CSS is loaded in the HEAD and the JS file is loaded just before the closing BODY tag. Where I want the menu to appear I have:

<div id="topMenu"></div>
<script>$('#topMenu').load('vgg_menu.html');</script>

I have all the files on a virtual server so nothing is being run locally. Here's the strange thing... the menu works awesome in IE8. In Chrome and FireFox, the parent menu items display and it's styled as it should be, but drop-down/sub-menu items don't work. HOWEVER... the menu will work after I open the Dev Tools panel. Go figure! I refresh the page, the menu doesn't work... I open the Dev Tool panel and the menu works.

Like I said, I've tried all the suggestions I found in other posts. It doesn't matter if I use "$(document).ready(function()" or not. It doesn't work. I've tried dynamically loading the CSS for the menu - no difference. Oh yeah... no errors in Dev Tools console either. If I enter the HTML for the menu right onto the index.html page, it works great in all browsers so there's nothing wrong with the code in the CSS or JS files.

Does anyone have any ideas why I cannot get this .load() to work properly in Chrome? Any guidance is much appreciated. Though it won't run, I've posted my code here .

An AJAX request, in your case via the jQuery load(url, complete) function , is asynchronous, meaning that it takes some time before the content from your .html file will be available for the dom, while the execution of your script continues. And that's the problem. When the document is ready you're calling adjustMenu before the elements are added to the dom. To fix this you simply have to pass adjustMenu to .load() as complete callback function. The complete callback will be called when the ajax request is completed.

$(document).ready(function() {
    $('#topMenu').load('menu.html', adjustMenu);

    $(".nav li a").each(function() {
        if ($(this).next().length > 0) {
            $(this).addClass("parent");
        };
    });

    $(".toggleMenu").click(function(e) {
        e.preventDefault();
        $(this).toggleClass("active");
        $(".nav").toggle();
    });
});

Updated your demo with these adjustments

PS: sorry for the incomplete comment earlier, just took a quick look at your code...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM