【问题标题】:Monaca Javascript not workingMonaca Javascript不起作用
【发布时间】:2017-08-10 13:40:30
【问题描述】:

我有以下代码,显示的简单 js 不起作用。如何让js在monaca工作?

这是我正在做的事情的代码。

顺便说一下,我已经从配置屏幕添加了 jQuery (Monaca 版本) 版本: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>

【问题讨论】:

    标签: javascript monaca


    【解决方案1】:

    根据我在您的代码中看到的情况,您在将 time 变量的值分配给 &lt;div&gt; 元素时出现了拼写错误。不是$("#countDown").txt(time);,是$("#countDown").text(time);

    此外,从您的函数名称来看 - countdown 我猜您正在尝试创建一个出现在屏幕上的计数器。在这种情况下,您不应该使用 setTimeout(function, period) 函数,因为它用于调用作为其参数传递的函数,仅在句点(作为第二个参数传递)通过后调用一次。因此,您应该使用setInterval(function(),period) 函数,该函数会在每次周期过去时调用该函数。因此,您应该使用clearInterval() 而不是clearTimeout()

    您的代码应如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 2015-11-07
      相关资源
      最近更新 更多