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>
答案 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)
<!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;
你想要这样的东西吗?
答案 2 :(得分:0)
试试此代码
if navigationController?.topViewController != self {
return
}