将动态检索的内容添加到jQuery Mobile PHP MVC到jQuery对象


Adding dynamically retrieved content to a jQuery Mobile PHP MVC to the jQuery object

我有一个MVC web应用程序,使用PHP检查查看查询字符串中的内容,并通过渲染标题,内容和页脚加载适当的页面(例如?category=1加载一个呈现类别视图的CategoryController)。

我还有一个custom.js,它将jQuery功能添加到DOM中的元素中。由于动态内容是由PHP控制的,所以jQuery功能只有在页面首先加载时才会起作用。遍历应用程序不会刷新页面,因此新包含的元素不会添加到jQuery对象中。

有什么办法解决这个问题吗?

首先不要在jQuery Mobile中使用$(function()$(document).ready(),因为jQM不是这样构建的。相反,您应该使用这里提到的页面事件:https://stackoverflow.com/a/14010308/1848600或mobileinit事件,如下所示:

$(document).on("pageinit", function () {
});

或mobileinit,如果你想在应用程序执行时只执行一次:

$(document).on("mobileinit", function () {
});

原因在顶部链接中描述。您还可以在jQM官方文档中找到更多相关信息:http://jquerymobile.com/test/docs/api/events.html

现在,如果你想让jQM重新设计你的页面样式,你应该使用.trigger(' pageccreate ')函数。例如,您有一个id为索引为的jQM页面,这是您生成的布局。
<div data-role="page" id="index">
    <div data-theme="a" data-role="header">
        <h3>
            First Page
        </h3>
        <a href="#second" class="ui-btn-right">Next</a>
    </div>
    <div data-role="content">
        <a href="#" data-role="button" id="test-button">Test button</a>
    </div>
    <div data-theme="a" data-role="footer" data-position="fixed">
    </div>
</div>  

要强制jQM设置样式,您应该使用如下命令:

$('#index').live('pagebeforeshow',function(e,data){    
    $('#index').trigger('pagecreate');
});

或者如果您想将它应用到每个jQM页面,那么像这样使用它:

$('[data-role="page"]').live('pagebeforeshow',function(e,data){    
    $(this).trigger('pagecreate');
});