1

I see some others (e.g. this post) have had trouble using external javascript scripts in JQuery Mobile - as of today I have joined their ranks.

I have a single external js script (controllers.js) which contains code that affects several pages on the site. It is loaded on every page of the site. I put the js file just before the tag it works fine on the initial page load. However when I navigate thereafter (using the JQM Ajax methods) all functions in the script stop working. I would have thought the script would remain in cache - but heyho. Anyhow there's an FAQ which answers this question and I've implemented their suggestion which is: "...to reference the same set of stylesheets and scripts in the head of every page." I have done this but when I do even on the first page load the js doesn't fire. There aren't page specific scripts - so the remainder of that FAQ does not apply.

My cut down html looks like this:

<!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>

and within the javascript file

controllers.js

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

Any ideas on what I may be doing wrong here?

4

1 回答 1

2

由于 ajax 中的内容#page是通过 ajax 动态加载的,因此 click 不起作用,因为它仅适用于调用脚本时页面上的元素。

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

$('body').on('click','#some_btn',function()
{
    alert('button pressed');
});
于 2013-08-18T15:17:42.467 回答