输入/输出非常基本的JS

时间:2017-10-11 16:04:57

标签: javascript

JS中的第一个程序。我不明白为什么我在第二个脚本中看不到条件的输出。谢谢你,先发制人道歉但不知道我在寻求帮助是什么。

    <!DOCTYPE html>
    <head>
    <script>
    function init() {
        var num = window.prompt("Enter a number");
        num_span = document.getElementById("entered_num");
        num_span.innerHTML = num;
    }
    </script>
    </head>
    
    <body onload="init()">
    
    <h1>We math!</h1>
    
    Your number is
    <p id ="here">MEMEME</p>
    perfect!
    
    <script>
    function isPerfect(n){
        var snowball = 1;
        var half_n = n >> 1;
        for (var k = 2; k <= half_n; k++){
            if (n % k == 0) {
                snowball += k;
            }
        }
        return (snowball == n);  
    }
    
    if (!isPerfect(num)) {
        document.getElementById("here").innerHTML = "not";
    } else {
        document.getElementById("here").innerHTML = "definitely";
    }
    </script>
    </body>

3 个答案:

答案 0 :(得分:1)

if(!isPerfect(num))的逻辑只执行一次,即加载页面时。您希望逻辑在用户提供数字后执行。因此,您需要更改init方法:

    <!DOCTYPE html>
    <head>
    <script>
    function init() {
      var num = window.prompt("Enter a number");
      if (!isPerfect(num)) {
        document.getElementById("here").innerHTML = "not";
      } else {
        document.getElementById("here").innerHTML = "definitely";
      }
    }
    </script>
    </head>
    
    <body onload="init()">
    
    <h1>We math!</h1>
    
    Your number is
    <p id ="here">MEMEME</p>
    perfect!
    
    <script>
    function isPerfect(n){
        var snowball = 1;
        var half_n = n >> 1;
        for (var k = 2; k <= half_n; k++){
            if (n % k == 0) {
                snowball += k;
            }
        }
        return (snowball == n);  
    }
    
    </script>
    </body>

答案 1 :(得分:0)

&#13;
&#13;
<!DOCTYPE html>
<head>
<script>
function init() {
    var num = window.prompt("Enter a number");
    if (!isPerfect(num)) {
    document.getElementById("here").innerHTML = document.getElementById("here").innerHTML +  " not";
} else {
    document.getElementById("here").innerHTML = document.getElementById("here").innerHTML + " definitely";
}
}
function isPerfect(n){
    var snowball = 1;
    var half_n = n >> 1;
    for (var k = 2; k <= half_n; k++){
        if (n % k == 0) {
            snowball += k;
        }
    }
    return (snowball == n);  
}

</script>
</head>

<body onload="init()">

<h1>We math!</h1>

Your number is
<p id ="here"></p>
perfect!
&#13;
&#13;
&#13;

你想要这样的东西吗?

答案 2 :(得分:0)

试试此代码

if navigationController?.topViewController != self {
    return
}