输入文本框不断消失

时间:2013-08-10 16:20:26

标签: javascript html

我对javascript很陌生,我想知道为什么当我点击按钮时文本框会一直消失。

这是我的代码:

<html>
    <head>
    </head>
        <body>

            <script>

                function readBox() 
                {
                    var a = document.getElementById('a').value;
                    var b = document.getElementById('b').value;
                    document.write(Number(a) * Number(b));
                }

            </script>

            <input type='text' size='29' id='a' placeholder='Enter number here...'>
            <input type='text' size='29'id='b' placeholder='Enter second number here...'>
            <input type='button' value='READ' onclick='readBox()'>

        </body>
<html>

如何将document.write()放在文本输入下,每次单击按钮时它都会更改?

4 个答案:

答案 0 :(得分:2)

不要使用document.write。它会删除整个文档。相反,有一个可以写入数据的元素,比如

<p id="output"></p>

然后像这样编码:

function readBox()
{
    var a = document.getElementById('a').value;
    var b = document.getElementById('b').value;
    document.getElementById("output").innerHTML = Number(a) * Number(b);
}

答案 1 :(得分:0)

    <html>
<head>
</head>
<body>

<script>

function readBox()
{
    var a = document.getElementById('a').value;
    var b = document.getElementById('b').value;
    document.getElementById('output').innerText=Number(a) * Number(b);
}


</script>

<input type='text' size='29' id='a' placeholder='Enter number here...'>
<input type='text' size='29'id='b' placeholder='Enter second number here...'>
<input type='button' value='READ' onClick='readBox()'>


<div id="output"></div>

</body>
<html>

document.write函数将删除整页然后将写入...

答案 2 :(得分:0)

你可以试试这段代码:

<html>
<head></head>
<body>

<script>

function readBox()
{
    var a = document.getElementById('a').value;
    var b = document.getElementById('b').value;
    //document.write(Number(a) * Number(b));
    document.getElementById('output').value = Number(a) * Number(b);
}
</script>

<input type='text' size='29' id='a' placeholder='Enter number here...'>
<input type='text' size='29'id='b' placeholder='Enter second number here...'>
<input type='text' size='29'id='output' placeholder='Output here...'>
<input type='button' value='READ' onClick='readBox()'>

</body>
<html>

U新输入一个输入结果。并通过函数readBox更改结果。

答案 3 :(得分:-1)

尝试这个..

<html>
<head>
</head>
<body>

<script>

function readBox()
{
    var a = document.getElementById('a').value;
    var b = document.getElementById('b').value;
    document.getElementById('output').innerText=parseInt(a) * parseInt(b);
}


</script>

<input type='text' size='29' id='a' placeholder='Enter number here...'>
<input type='text' size='29'id='b' placeholder='Enter second number here...'>
<input type='button' value='READ' onClick='readBox()'>

<input type='text' size='29' id='output' placeholder='answer...'>  // to show result here...


</body>
<html>