jQuery Mobile样式用于异步包含的div
我正在使用jQuery Mobile库开发一个移动网站。 我在主页上有一个页眉,一个页脚和一个内容区域,并使用以下代码将任何链接加载到内容区域:
$("a").click(function() { var toLoad = $(this).attr('href'); // Loading image $('#content-body').html('<img src="https://stackoverflow.com/questions/8361705/jquery-mobile-styles-for-an-asynchronously-included-div//img/ico/loader.gif" />
'); $('#content-body').load(toLoad);
这很好,除了jQuery Mobile样式不适用于这种方式包含的内容。 例如, home
包含按钮:
Inventory
但是当我将该页面异步加载到content
div中时,链接不会显示为按钮。 有没有办法告诉jQuery Mobile每次重新加载#content
应用移动样式?
你确定可以。 您想使用.trigger('create')
初始化任何jQuery Mobile小部件:
$("a").click(function() { var toLoad = $(this).attr('href'); // Loading image $('#content-body').html('
'); $('#content-body').load(toLoad, function () { $(this).trigger('create');//it's that easy :) }); });
请注意,您要在要初始化的窗口小部件的父元素上调用.trigger('create')
。 另请注意,由于您通过异步函数加载内容,因此需要在.trigger('create')
.load()
调用的回调函数中调用.trigger('create')
,以便在尝试初始化它们时实际存在要初始化的元素。 。
此外,您有时会遇到一个问题,即窗口小部件已初始化但后来您更改了它的HTML并希望更新窗口小部件。 有这样的function,例如: .listview('refresh')
.slider('refresh')
等。
我刚回答了一个关于需要初始化或刷新的小部件的问题: 如何刷新jquery移动列表视图
此外,您还需要将.delegate()
更改为.delegate()
以便通过AJAX加载的链接也会附加此事件处理程序:
$('#content-body').delegate('a', 'click', function() { var toLoad = this.href;//no need to use jQuery here since `this.href` will be available in all major browsers // Loading image $('#content-body').html('
'); $('#content-body').load(toLoad, function () { $(this).trigger('create');//it's that easy :) }); });