自动检查过程

时间:2019-02-27 16:52:46

标签: javascript

下面的代码使我返回“偶”或“奇”,但我必须经常更改,他要检查25到115并在页面正文中显示结果该怎么做?

<html>
    <title>FrontPage</title>
    </head>
    <body>
    <form method="post" name="Form1" onsubmit="Check();">
      <input type="submit" value="Submit" name="bSubmit"></p>
    </form>
    
    <script type="text/javascript">
    function Check() {
    var n = "26";
    var finish = n/2;
    
    if(n & 1){
        alert("Impar");
    } else {
        alert("Par");
    }
    alert(finish);
    }
    </script>
    </body>
    </html>

3 个答案:

答案 0 :(得分:1)

var btn = document.querySelector('#btn');
var result = document.querySelector('#result');

btn.addEventListener('click', function() {
  for (var i = 25; i <= 115; i++) {
    var li = document.createElement('li');
    li.innerText = i.toString() + ' - ' + ((i & 1) ? 'Impar' : 'Par');
    result.append(li);
  }
});
<input id="btn" type="submit" value="Submit" name="bSubmit">
<ul id="result"></ul>

答案 1 :(得分:1)

只需在for循环内实现代码(因为您确切知道需要多少次迭代):

document.querySelector('#btnSubmit').addEventListener('click', function(e) {
  var min = 25;
  var max = 115;
  var i;
  for (i = min; i <= max; i += 1) {
    console.log(check(i));
  }
});

function check(n) {
  var s = `${n} is `;
  s += n % 2 === 0 ? "even" : "odd";
  return s;
}

check();
<input id="btnSubmit" type="button" value="Check" />

答案 2 :(得分:0)

您需要像这样使用foor循环:

const append = str => document.getElementById('print').innerHTML += str;

document.getElementById('btn').addEventListener('click', function () {
  for (let i = 25; i <= 115; i++) {
    const result = i % 2 === 0 ? 'even' : 'odd';
    append(`<p>Number ${i} is ${result}</p>`);
  }
});
<button id="btn">Result</button>
<div id="print"></div>