大家好,我们有一个任务,用户只输入200以内的任何值,如果是质数,就应该打印素数,如果不是,就不打印素数。我已经精确地更改了代码。然而,它并不起作用。为甚麽呢?
<!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的初学者。请帮帮我;-;
发布于 2021-03-24 19:49:19
你不能在JavaScript中内联超文本标记语言,比如if (primeprinter === true){ <p> Prime </p> } else { <p> Not Prime </p> }不能工作。您可以手动操作DOM。
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";
}<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>
https://stackoverflow.com/questions/66777748
复制相似问题