Jquery Mobile Javascript not working on ajax load

我的梦境 提交于 2019-12-29 09:06:47

问题


Have the following markup in my html page to toggle a search bar based on if a search icon is clicked:

<a id="searchIcon" href="/"></a> 

<div id="searchWrapOuter" style="display:none;">
    <div id="searchWrapInner">
        <div id="formContainer">
            <form id="searchForm" action="#">
                <div>
                    <input type="search" name="search-mini" id="search-mini" value="" data-mini="true" />
                </div>
            </form>
        </div>
    </div>
</div>

Width the following javascipt/jquery:

 $(function() {
        $(document).on("click", "#searchIcon", function () {
            var searchWrapper = $("#searchWrapOuter");
            $(searchWrapper).slideToggle();
            return false;
        });
});

This code works as expected on a page load direct off a Url. When coming into the page off a link which is Ajax loaded, loads the contents of the page into the DOM, and the DOM ready handler only executes for the first page.

I have read about using the

$(document).on('pageinit'), not $(document).ready()/$(function()

I still haven't been able to get this to work when coming in off an ajax link however. What would be the correct way to implement these events to get the code to work coming in from an Ajax link?

Thanks,


回答1:


Most likely it is because you are using IDs instead of classes. jQuery Mobile doesn't work well with IDs because it caches pages into the DOM so if you open a page, close it, then go back to the page, you might have your page twice inside the DOM (one visible, one hidden/cached). So when you do $("#searchWrapOuter") you don't know which element you are actually dealing with (in your case, probably the hidden one).

The solution is to change your IDs to classes. This is not very intuitive but I found that is the best way to work with jQuery Mobile.

Also note this comment in the doc which might also be relevant to you:

The id attribute of all your elements must be not only unique on a given page, but also unique across the pages in a site. This is because jQuery Mobile's single-page navigation model allows many different "pages" to be present in the DOM at the same time. This also applies when using a multi-page template, since all "pages" on the template are loaded at once.

http://jquerymobile.com/demos/1.2.0/docs/pages/page-anatomy.html




回答2:


You can manually adjust delay time to 500ms and 1s.

$(searchWrapper).delay(1000).slideToggle(); 



回答3:


My issue is that the page id was below the pages tags. So once I moved the page div above it, the javascript was included in the ajax page load. Previous to this



来源:https://stackoverflow.com/questions/14316113/jquery-mobile-javascript-not-working-on-ajax-load

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!