Javascript问题$(文档).on / live / bind无效

时间:2012-11-15 13:55:46

标签: jquery-mobile page-init

我尝试在通过ajax调用加载的页面上实现随机答案。我正在使用jquery mobile包含布局。因此,我在div data-roll容器中添加了一个简单的java脚本,并通过$(document).live或$(document).on或$(document).bind初始化它,就像它应该根据这里的许多答案或建议一样。当我使用普通的警报功能时,一切正常。喜欢这个

<script>
    $(document).live('pageinit', "#answerPage", function (event) {
               alert("Page Initialized");
         });
</script>

当我将它添加到普通的html页面时,我的脚本也能正常工作。

所以当我改为使用警报时,我使用函数getanswer()它不起作用。我在这做错了什么?谢谢你的帮助。

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Title</title> 

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

    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>

    </head> 
<body>

<div data-role="page" id="answerPage" data-theme="b" data-add-back-btn="true">

     <script>
    $(document).on("pageinit", "#answerPage", function(event) {
            function getanswer() {
                    var r_text = new Array ();
                        r_text[0] = "A";
                        r_text[1] = "B";
                        r_text[2] = "C";
                        r_text[3] = "D";
                        r_text[4] = "E";
                        r_text[5] = "F";
                        r_text[6] = "G";
                    var i = Math.floor(7*Math.random());
                    document.getElementById("ShowAnswer").innerHTML = r_text[i];
                    };

          });
     </script>

     <div data-role="header" data-position="fixed" data-theme="b">
         <div id="ShowAnswer"> </div>   

     </div>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您忘了拨打您的电话getanswer() ...
working example

<!DOCTYPE html>
<html>
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test</title>
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
  <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
  <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>

<body>
  <div data-role="page" id="answerPage" data-theme="b" data-add-back-btn="true">
     <div data-role="header" data-position="fixed" data-theme="b">
       <div id="ShowAnswer"></div>
     </div>
  </div>

  <script>
    $(document).on("pageinit", "#answerPage", function(event) {
      getanswer();
    });

    function getanswer() {
      var r_text = new Array ();
      r_text[0] = "A";
      r_text[1] = "B";
      r_text[2] = "C";
      r_text[3] = "D";
      r_text[4] = "E";
      r_text[5] = "F";
      r_text[6] = "G";
      var i = Math.floor(7*Math.random());
      document.getElementById("ShowAnswer").innerHTML = r_text[i];
    };
   </script>
</body>
</html>