2012-11-15 45 views
2

我試圖在通過ajax調用加載的頁面上實現隨機答案。我正在使用jQuery手機包容性佈局。因此,我在div數據卷容器中添加了一個簡單的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> 

回答

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>