2

我对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

4 回答 4

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);
}
于 2013-08-10T16:23:21.827 回答
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 NEW 一个输入来放置您的结果。并通过函数 readBox 更改结果。

于 2013-08-10T16:34:07.893 回答
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 函数将擦除整个页面,然后将写入...

于 2013-08-10T16:26:49.607 回答
-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>
于 2013-08-10T16:41:38.007 回答