2017-03-19 4 views
0

私は以下のコードを持っています。単純なjsは動作していません。どのように私はモナカで仕事をするのですか?Monaca Javascriptが機能しない

ここは私がやっていることのコードです。

ところで、設定画面からjQuery(Monaca Version)バージョン:2.0.3を追加しました。

<!DOCTYPE HTML> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> 
    <meta http-equiv="Content-Security-Policy" content="default-src * data:; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'"> 
    <script src="components/loader.js"></script> 
    <script src="lib/onsenui/js/onsenui.min.js"></script> 

    <link rel="stylesheet" href="components/loader.css"> 
    <link rel="stylesheet" href="lib/onsenui/css/onsenui.css"> 
    <link rel="stylesheet" href="lib/onsenui/css/onsen-css-components.css"> 
    <link rel="stylesheet" href="css/style.css"> 

    <script> 
    //this starts the count down. 
    //time should be in seconds 
    function countDown(time){ 
     $("#countDown").txt(time); 
     var timeout=setTimeout(function(){ 
      time--; 
      $("#countDown").txt(time); 
      if(time==0) clearTimeout(timeout); 
     }, 1000); 
    } 

    ons.ready(function() { 
     countDown(10); 
    }); 

    </script> 
</head> 
<body> 
    <div id="countDown"></div> 
</body> 
</html> 

答えて

1

私はあなたのコードで表示されるものと、あなたは<div>要素にtime変数の値を割り当てる際にタイプミスをしてきました。 $("#countDown").txt(time);ではなく、$("#countDown").text(time);です。

また、機能の名前から判断すると - countdown私はあなたが画面に表示されるカウンタを作成しようとしていると思います。その場合は、setTimeout(function, period)関数を使用するべきではありません。これは、引数として渡された関数を呼び出すのに使用されるため、期間(2番目の引数として渡された後)が1回だけ渡されます。したがって、期間が経過するたびに関数を呼び出すsetInterval(function(),period)関数を使用する必要があります。したがって、clearTimeout()の代わりにclearInterval()を使用する必要があります。

あなたのコードは次のようになります。

<script> 
    //this starts the count down. 
    //time should be in seconds 
    function countDown(time){ 
     $("#countDown").text(time); 
     var timeout=setInterval(function(){ 
      time--; 
      $("#countDown").text(time); 
      if(time==0) clearInterval(timeout); 
     }, 1000); 
    } 

    ons.ready(function() { 
     countDown(10); 
    }); 
</script> 
関連する問題