-1
<!DOCTYPE html>
<html>
<head>
<title>input number</title>
</head>
<body>

enter no:1<input id="t1" type="text"><br>

<button type="button" onClick="myFunction()">submit</button>
<button type="button" onClick="myFunction()">next</button>

<div id="div1" style="color:#0000FF">
</div>

<script>
function myFunction(){

var no=document.getElementById("t1").value;

if(no==""||isNaN(no))
{
    alert("Not Numeric");
}

else{

    if(no!=1){

        if(no%2==0){

        no=no/2;
    }
    if (no%2!=0) {

        no=(no*3)+1;
    }
}
}


document.getElementById("div1").innerHTML = no;
}

</script>

</body>
</html>

在我按下提交按钮时在文本框中输入数字后,它显示以下输出

输入编号:1
提交下一个
16

但是当我按下下一个按钮时它没有显示任何输出。我的预期输出是当我按下下一个按钮时它应该显示下一个。通过执行 myFunction() 函数中的逻辑。帮助...

4

3 回答 3

1

你还没有为当 no = 1 设置任何案例。当 no = 1 和当 no%2 != 0 时,你有一个案例,当 no = 1 时这两者都是假的。这里没有任何增量逻辑找到下一个数字并返回它。no%2==0我认为您在子句末尾缺少 } 。

我也看不出为什么你在这里有两个相同的按钮,下一步和提交做同样的事情。此外,我建议使用更具描述性的 ID。div1 不是 div 的好名字。

于 2013-09-01T16:54:48.373 回答
0

如果打算实现 Collat​​z 猜想,则 javascript 部分应如下所示。http://en.wikipedia.org/wiki/Collat​​z_conjecture

function myFunction(){
    var no=document.getElementById("t1").value;

    if(no==""||isNaN(no)) {
        alert("Not Numeric");
    } else {
        if(no!=1) {
            if(no%2==0) {
                no=no/2;      // Note the division operator instead of mod
            } else {
                no=(no*3)+1;
            }
        }
    }
    document.getElementById("t1").value = no; // Note that we are writing to the textbox
}
于 2013-09-01T17:03:52.630 回答
0

也有一些基本的 HTML 问题,在您的帖子中,您使用输入标签作为

<input id="t1" type="text">将其用作:<input id="t1" type="text" />

其次,当您将数据提交给函数时,您在那里有一些价值!也许 1 是值或 16,无论如何。但是当您尝试重新提交时,要么不允许,要么您的输入现在是一个空字段。因此,该功能不会比这一步执行得更远:

if(no==""||isNaN(no))

尝试将值保存在表单中。

尝试使用这个:

document.getElementById("t1").value = no;

确保按原样捕获该值,因为您的代码正在将该值更改为其他形式,为此请使用新变量。这将保存输入中的值并再次将其写回该输入。

这将设置该文本输入的值,就像它在函数之前一样。它可能会使输入再次准备好提交!

于 2013-09-01T17:23:44.233 回答