首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用js的Prime Printer?

使用js的Prime Printer?
EN

Stack Overflow用户
提问于 2021-03-24 17:01:24
回答 1查看 32关注 0票数 0

大家好,我们有一个任务,用户只输入200以内的任何值,如果是质数,就应该打印素数,如果不是,就不打印素数。我已经精确地更改了代码。然而,它并不起作用。为甚麽呢?

代码语言:javascript
复制
<!DOCTYPE html>
<html>
<body>

<script>
  function doAction(){

    //gets the value from the text field with id input1 and stores it in variable num1
    var num1 = document.getElementById("input1").value;



    //HINT: loop through some finite number and check whether they are prime
    //You can create a function out of the CheckPrime exercise and use that to check if a number is 
Prime

    //for loop the numbers until you satisfy the num1

    function primeprinter(num1) {
  for(var i = 2; i < num1; i++)
    if(num1 % i === 0) return false;
  return num1 > 1;

  if (primeprinter === true){
      <p> Prime </p>
  }
  else{
      <p> Not Prime </p>
   }
}





    //Challenges:
    //validate if the input are numbers. Hint: Check out isNaN() function
    //Validate the input to only be less than equal 200
  }


</script>

<h2>Prime Numbers Printer</h2>
Prints the first N prime numbers. Only try up to 200.
<br/>
<br/>
Input1: <input type="text" id="input1"/>
<button type="button" onclick="doAction()">
Print Prime</button>
<br/>
<br/>
Result:
<p id="output"></p>

</body>
</html> 

我是javascript的初学者。请帮帮我;-;

EN

回答 1

Stack Overflow用户

发布于 2021-03-24 19:49:19

你不能在JavaScript中内联超文本标记语言,比如if (primeprinter === true){ <p> Prime </p> } else { <p> Not Prime </p> }不能工作。您可以手动操作DOM。

代码语言:javascript
复制
function primeprinter(num1) {
  for (let i = 2; i < num1; i++)
    if (num1 % i === 0) return false;
  return num1 > 1;
}

function doAction() {
  const num1 = document.getElementById("input1").value;
  document.getElementById("output").innerHTML = primeprinter(num1) ? "Prime" : "Not Prime";
}
代码语言:javascript
复制
<h2>Prime Numbers Printer</h2>
<span>Prints the first N prime numbers. Only try up to 200.</span>
<br />
<br />
<label for="input1">Input1: </label><input type="text" id="input1" />
<button type="button" onclick="doAction()">Print Prime</button>
<br />
<br />
<span>Result:</span>
<p id="output"></p>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66777748

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档