我的目标是提示用户输入行数和列数以使用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>
答案 0 :(得分:0)
替换
while (isNaN(rows));
与
while (isNaN(rows) || (parseInt(rows) < 1) || (parseInt(rows) > 10) );
答案 1 :(得分: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) );
获取警报