JavaScript call function, not fire (the script title is jQuery and jQuery Mobile)

I have a page like this (index.php):

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
    <?php //add .min.js file when all programming done ?>
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/_jquery.mobile-1.4.0.css">

    <script src="js/_jquery-2.1.0.js" type="text/javascript"></script>
    <script src="js/_jquery.mobile-1.4.0.js" type="text/javascript"></script>

    <script src="js/main.js" type="text/javascript"></script>
    <script src="js/sign.js" type="text/javascript"></script>
</head>
<body>
<div data-role="page">
    <div data-role="header" id="nav"><?php include_once 'nav.ui.php'; ?></div>
    <div data-role="main" class="ui-content" id="ui">

        <input type="button" id="optionUpdate">

    </div>
    <div data-role="footer" id="footer"><?php include_once 'footer.ui.php'; ?></div>
</div>
</body>
</html>

And in main.js I have:

$('#optionUpdate').click(function () {
    optionUpdate();
});

function optionUpdate() {
    alert('hi');
}

The problem is this: when I click the button, the event does not fire. But if you add an event onclickto the button with optionUpdate();, it will work! What for? How can i fix this?

+3
source share
4 answers

Note: this answer is more about jQuery than jQuery Mobile. In the mobile library, the code that should run when the page is refreshed within the framework must use page events, as described in other answers.


"main.js" <head> , "optionUpdate" : .

:

  • :

    $(document).on('click', '#optionUpdate', optionUpdate);
    
  • "ready":

    $(function() {
      $('#optionUpdate').click(function () {
        optionUpdate();
      });
    });
    
  • <script> <body>.

+2

jQuery Mobile .ready(). , /.

jQuery Mobile Ajax , .ready(), .

: $(document).bind('pageinit'), $(document).ready():

, jQuery, - $(document).ready(), DOM. jQuery Mobile Ajax DOM , DOM ready . , , pageinit. .

.ready() jQuery Mobile pagecreate (pageinit 1.4). pagecreate , pagecreate.

$(document).on("pagecreate", function () {
  $('#optionUpdate').on("click", function () {
    optionUpdate();
  });

  function optionUpdate() {
    alert('hi');
  }
});

, .

$(document).on("pagecreate", ".selector or #page_ID", function () {
  /* functions for this page only */
});

+4

. DOM:

$(document).ready(function() { 
    $('#optionUpdate').click(function () {
        optionUpdate();
    });
});
-1

. Currentl, , .

$(document).ready(function() { 
    $('#optionUpdate').click(function () {
        optionUpdate();
    });
});

. .on() .

$(document).on('click', '#optionUpdate', function() { 
    optionUpdate();
});

, -, .

script ,

    <script src="js/main.js" type="text/javascript"></script>
    <script src="js/sign.js" type="text/javascript"></script>
-2

All Articles