1

我的目标是提示用户输入行数和列数以使用 Javascript 生成表格(请参阅下面的代码)。但是,行数/列数的范围应为 1 到 10(使用parseInt()& isNaN)。如果用户输入了超出该范围的数字,应该会出现“行号超出范围 - 再试一次,页面将重新加载”的警告,然后location.reload()将使用“ ”。我已经尝试了很多次,但都失败了。我是 Javascript 初学者,请帮帮我。

    <script type="text/javascript">
    var rows;
    var cols;
    do
    {
    rows = prompt("How many rows? 1-10");
    }
    while (isNaN(rows));

    do
    {
    cols = prompt("How many columns? 1-10");
    }
    while (isNaN(cols));

    </script>
    <style type="text/css">
    <!--
    table {
      border-spacing: 0px;
      width: 500px;
      border-collapse: collapse;
      margin: 20px auto;

    }
    td {
      border: solid 1px grey;      
    }
    -->
    </style>
  </head>
  <body>
    <table>

    document.write('<table border="1" cellspacing="1" cellpadding="2">');

    for(var i = 1; i <= rows; i++)
    {
       document.write('<tr>');    
       for( var x = 1; x <= cols; x++ )
    {
       document.write("<td>"+ ( i * x ) + "</td>");
        }
       document.write('</tr>');
    }

    document.write('</table>');

    -->
        </script>
4

2 回答 2

0

代替

    do
    {
    rows = prompt("How many rows? 1-10");
    }
    while (isNaN(rows));

    do
    {
    cols = prompt("How many columns? 1-10");
    }
    while (isNaN(cols));

    do
    {
    rows = prompt("How many rows? 1-10");
    if(isNaN(rows))
         alert("Row No. Should be a number");
    if((parseInt(rows) < 1) || (parseInt(rows) > 10))
        alert("Row No. Out of Range - Try Again");
    }
    while (isNaN(rows) || (parseInt(rows) < 1) || (parseInt(rows) > 10) );

    do
    {
    cols = prompt("How many columns? 1-10");
    if(isNaN(cols))
         alert("Col No. Should be a number");
    if((parseInt(cols) < 1) || (parseInt(cols) > 10))
        alert("Col No. Out of Range - Try Again");
    }
    while (isNaN(cols) || (parseInt(cols) < 1) || (parseInt(cols) > 10) );

警觉

于 2013-04-03T07:52:45.997 回答
0

代替

while (isNaN(rows));

while (isNaN(rows) || (parseInt(rows) < 1) || (parseInt(rows) > 10) );
于 2013-04-03T07:36:49.887 回答