【问题标题】:why this html javascript file doesnt work and how can i make user input to not be anything but positive number?为什么这个 html javascript 文件不起作用,我怎样才能让用户输入不是正数?
【发布时间】:2022-01-25 06:26:38
【问题描述】:

我尝试了一些东西,但它们都不起作用,它不计算面积,我想让用户输入为正数,如果写了其他内容,则发送错误

<!DOCTYPE html>
<html>

<head>

<title> Area of circle </title>

</head>

<body>
<script type="text/javascript">
<meta charset="UTF-8">

    function CalculateArea(){
    var r = document.form1.txtr.value;
    var area = (r * r * Math.PI);
    document.write("<P> Area is:" + area +"</P>")
}

</script>

<form name=form1>
    Type radient of circle:
    <input type="text" name="txtr" size=10>
    <br>
    <input type="button" value="Calculate" onClick='CalculateArea;'>
</form>
</body>
</html>

【问题讨论】:

标签: javascript html


【解决方案1】:

首先你需要将 () 添加到你的函数调用中。第二,它是

而不是

,第三你可能不想使用 document.write。

function CalculateArea(){

    var r = document.getElementById('form1').value;
    let p = document.getElementById('area')
    var area = (r * r * Math.PI);
    if (r%1 !=0 || r < 1) p.innerHTML = 'Please enter a whole number greater than 0';
    else p.innerHTML = area;
}
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">


<title> Area of circle </title>

</head>

<body>


<form id='form1'>
    Type radient of circle:
    <input type="text" name="txtr" size=10>
    <br>
    <input type="button" value="Calculate" onClick='CalculateArea()'>
    <p id='area'></p>
</form>
</body>
</html>

【讨论】:

  • 谢谢你的工作,你帮我用这个函数只需要整数,如果输入它会返回错误
  • sn-p 更新
  • &lt;p&gt;&lt;P&gt; 是相同的。 HTML 不区分大小写。
【解决方案2】:

document.addEventListener('DOMContentLoaded', () => {
  const inputElem = document.querySelector('#radius');
  const buttonElem = document.querySelector('#button');
  const outputElem = document.querySelector('#output');
  
  buttonElem.addEventListener('click', () => {
    const r = inputElem.value;
    if (r >= 0 && r % 1 === 0) {
      outputElem.innerHTML = calcArea(r);    
    } else {
      alert('Please enter a positive, whole number radius.');
    }
  });
});

function calcArea(r) {
  return r * r * Math.PI;
}
<!DOCTYPE html>
<html>
<head>
  <title>Area of circle</title>
  <meta charset="UTF-8">
</head>
<body>
  <input type="text" id="radius"></input>
  <input type="button" id="button" value="Calculate"></input>
  <div id="output"></div>
</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多