在javascript中再次调用函数

时间:2013-09-01 16:42:55

标签: javascript html

<!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>

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

输入no:1
提交下一个 16

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

3 个答案:

答案 0 :(得分:1)

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

此外,我不明白为什么你在这里有两个相同的按钮,然后提交做同样的事情。此外,我会建议更多的描述性ID。 div1不是div的好名字。

答案 1 :(得分:0)

如果打算实施Collat​​z猜想,javascript部分应如下所示。 http://en.wikipedia.org/wiki/Collatz_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
}

答案 2 :(得分:0)

还有一些基本的HTML问题,在您的帖子中,您使用输入标记

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

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

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

尝试将值保存在表单中。

尝试使用:

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

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

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

相关问题