JqueryMobile在正文中加载外部脚本并不能解决我的ajax导航问题

时间:2013-08-18 15:06:20

标签: jquery-ui jquery jquery-mobile

我看到其他一些人(例如this post)在JQuery Mobile中使用外部JavaScript脚本时遇到了麻烦 - 截至今天我已加入他们的行列。

我有一个外部js脚本(controllers.js),其中包含影响网站上多个页面的代码。它加载在网站的每个页面上。我把js文件放在标签之前它在初始页面加载时工作正常。但是当我之后导航(使用JQM Ajax方法)时,脚本中的所有函数都停止工作。我原本以为脚本会保留在缓存中 - 但是heyho。无论如何有一个FAQ回答了这个问题,我已经实现了他们的建议:“......在每个页面的头部引用相同的样式表和脚本集。”我已经这样做但是当我甚至在第一页加载时,js不会触发。没有特定于页面的脚本 - 因此该FAQ的其余部分不适用。

我的剪切html看起来像这样:

<!doctype html>
    <head>
       <meta charset="utf-8">
       <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

        <meta name="viewport" content="width=device-width,initial-scale=1.0">

        <link rel="stylesheet"  href="/static/jquery-ui-1.10.3.custom.min.css">
        <link rel="stylesheet"  href="/static/jquery-mobile/css/themes/default/jquery.mobile-1.3.2.min.css">

        <script src="/static/jquery-1.9.1.min.js"></script>
        <script src="/static/jquery-ui/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script>
        <script src="/static/jquery-mobile/js/jquery.mobile-1.3.2.min.js"></script>

      <!-- CSS: implied media="all" -->
    </head>


    <body>
        <div data-role="page" id = "main-page">

            <div data-role="header" style="overflow:hidden;">
            </div>

            <div id = "home" data-role="content">
                <input type ='button' id = "some_btn" value="press me">
            </div>

        </div>
        <script type="text/javascript" src="/static/js/controllers.js"></script>
    </body>
</html>

并在javascript文件中

controllers.js

$('#some_btn').click(function()
{
    alert('button pressed');
});

关于我在这里做错了什么的想法?

1 个答案:

答案 0 :(得分:2)

由于#page中的内容是通过ajax动态加载的,因此单击将无效,因为它仅适用于调用脚本时页面上的元素。

您需要使用.on()方法:

$('body').on('click','#some_btn',function()
{
    alert('button pressed');
});