建立乘法口诀表

发布于 2025-01-16 23:12:40 字数 12549 浏览 0 评论 0原文

我在编写要求用户输入起始值和结束值的计算器时遇到问题。程序必须使用嵌套的 for 循环。包括行标签和列标签。

这就是决赛桌的样子。我将非常感谢相关视频的链接或解决此问题的提示。例如,从 1 到 3 的输出可能如下所示:

    1   2   3
1   1   2   3
2   2   4   6
3   3   6   9

从 3 到 5 的输出可能如下所示:

    3   4   5
3   9  12  15
4  12  16  20
5  15  20  25

乘数应出现在表格的顶部和左侧。

我尝试根据我的任务修改一个示例。

var result = 'x ';
for (var i = 0; i < 11; i++) {

    for (var j = 0; j < 11; j++) {

        if(i == 0 && j > 0){
          result += '[' + j + ']';
        } 
        else if(j == 0 && i>0){
          result += '[' + i + '] ';
        } 
        else if(i>0 && j>0){
        result += (i*j) + ' ';
        }
    }
    result += '\n'
}

console.log(result);

输出:

x [1][2][3][4][5][6][7][8][9][10]

[1] 1 2 3 4 5 6 7 8 9 10 

[2] 2 4 6 8 10 12 14 16 18 20 

[3] 3 6 9 12 15 18 21 24 27 30 

[4] 4 8 12 16 20 24 28 32 36 40 

[5] 5 10 15 20 25 30 35 40 45 50 

[6] 6 12 18 24 30 36 42 48 54 60 

[7] 7 14 21 28 35 42 49 56 63 70 

[8] 8 16 24 32 40 48 56 64 72 80 

[9] 9 18 27 36 45 54 63 72 81 90 

[10] 10 20 30 40 50 60 70 80 90 100 

我注意到乘数在括号中,X 出现在左上角。是通过if语句实现的吗?在我的作业中,必须有一个空单元格而不是 X。这就是我的想法:

let result = "x";
for(let row = number1; row <= number2; row++){
     result += row + "<tr>";
        
   for( let column = number1; column <= number2; column++){
       result += "<td>" + row * column +"</td>";            
    }
        result += "<br>"
     result += "</tr>"
 }
  document.getElementById("output").innerHTML = result;
}

我的程序生成一个测试表,其起始值等于 2,结束值等于 5,看起来像这样

x 4 6 8 10

6 9 12 15

8 12 16 20

10 15 20 25

:很明显,代码中公式中的某些逻辑不正确。 我试图使用 document.getElementById() 输出结果表。这是要求之一。非常感谢一些解释表格元素标签使用的评论。 该程序必须采用起始值和最终值,而不仅仅是 1 到 10。

我感谢大家的回答。代码中的一些注释解释了我做错了什么以及我做错了什么,也是受欢迎的。

附注 我对我的代码做了一些更正。现在显示正常了。有一点是不对的。它以比起始数字大 1 的数字开始计算(例如,对于输入值 2 到 6,它将显示 3 到 6)。有什么想法吗?

function displayExpressions(){
    let number1 = getNumber();
    // console.log(number1)
    let number2 = getExpressionsNumber();
    // console.log(number2)
    if (number1 ==0 || number2 == 0){
        document.getElementById("error").innerText =  "Enter a number!" 
    }
    else{
    let result = " "
    for(let row = number1; row <= number2; row++) {
         result += "<tr>";            
       for( let column = number1; column <= number2; column++){           
           if( row == number1 && column > number1){
               result +=  "<th>" + column + "</th>";
           }
           else if(column == number1 && row > number1){
               result += "<th>" + row + "</th>";
           }
           else if (row == number1 && column == number1){
               result =  "<td>" + "x" + "</td>";
           }
           else{
             result += "<td>" + row * column +"</td>";
             document.getElementById("output").innerHTML = result;
           }
       }           
         result += "</tr>";      
     }
      document.getElementById("output").innerHTML = result;
     }
}  

我感谢所有提供帮助的人。这是一个工作示例。

'use strict';

window.addEventListener('load', function () {
  document.getElementById('number1').addEventListener('focus', inputFocus);
  document.getElementById('number2').addEventListener('focus', inputFocus);
  document.getElementById('btn').addEventListener('click', main);
  document.getElementById('number1').focus();
});
function inputFocus() {
  document.activeElement.select();
  document.getElementById('error').innerText =
    'Enter ' + document.activeElement.id + ' value.';
}
function getNumber() {
  let multiplier = document.getElementById('number1').value;
  multiplier = Number(multiplier);
  return multiplier;
}
function getExpressionsNumber() {
  let expressionsNumber = document.getElementById('number2').value;
  expressionsNumber = Number(expressionsNumber);
  return expressionsNumber;
}
// I have a good feeling that checkInput() does not work at all and is most likely redundant.
function checkInput() {
  let number = document.activeElement.value;
  console.log(number);
  if (isNaN(number) || number.trim().lenght == 0) {
    document.getElementById('error').innerText = 'Enter a number!';
    return false;
  }
  return true;
}
function main() {
  console.log('Main is called...'); // testing to see if this function is being called.
  console.log(checkInput()); // testing if this function returns true...
  if (checkInput()) {
    document.getElementById('error').innerText = ''; // set the error message to emptry string... good.
    displayExpressions(); // call the function to display the output...
  }
}

function multiplication(number, expressionsNumber) {
  let result = number * expressionsNumber;
  return result;
}

function displayExpressions(){
    let number1 = getNumber();
    // console.log(number1)
    let number2 = getExpressionsNumber();
    // console.log(number2)
    if (number1 <=0 || number2 <= 0){
        document.getElementById("error").innerText =  "Enter a natural number!" 
    }
    else if(number1 >= number2 ){
        document.getElementById("error").innerText =  "End value must be grater than Start value!" 
    }
    else{
    let result = " "
    for(let row = number1; row <= number2 + 1; row++) {
         result += "<tr>";            
       for( let column = number1; column <= number2 + 1; column++){           
           if( row == number1 && column > number1){
               result +=  "<th>" + (column-1) + "</th>";
           }
           else if(column == number1 && row > number1){
               result += "<th>" + (row - 1) + "</th>";
           }
           else if (row == number1 && column == number1){
               result =  "<th>" + "x" + "</th>";
           }
           else{
           result += "<td>" + (row - 1) * (column-1) +"</td>";
               document.getElementById("output").innerHTML = result;
           }
       }           
         result += "</tr>";      
     }
      document.getElementById("output").innerHTML = result;
    }
}  
  
   
*{
    box-sizing: border-box;
}

.fcontainer{
    display: flex;
}   

div.fcontainer{
    justify-content: space-between;
    flex-basis: 50%;
    margin: 15px;
    
}

body {
    margin: 40px;
    background-color: rgb(230, 255, 247);
    font-family: 'Roboto', sans-serif;
    font-size: calc(10px + (24 - 10) * (100vw - 300px) / (1600 - 300));
}

h1, h2 {
    text-align: center;
}

img {
    display: block;
    width: 300px;
    margin: 0 auto;
}

a {
    text-decoration: none;
}

p {
    margin: 10px 0px;
}

button {
    margin: 10px 0px;
}

div.calc {
    margin: 0 auto;
    display: block;
    width: 600px;
    background-color: rgb(33, 209, 150);
    padding: 20px;
    border-radius: 5px;
    text-align: center;

}


div.calc p {
    text-align: left;
    margin-left: 55px;
}

.calc input {
    width: 80%;
    text-align: right;
    border-radius: 3px;
    border: none;
}

div.cal h2,
 h3 {
    text-align: center;
}
#assignment6 div{
    margin-top: 10px;
}

div.calc div input,
div.calc div label{
    width: 45%;
display: inline-block;
text-align: right;



}

.calc button {
    margin-left: 355px;
    border-radius: 5px;
    border:2px solid #008CBA;
    color: black;
    padding: 16px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    transition-duration: 0.4s;
    cursor: pointer;
}

.calc button:hover {
    background-color: #008CBA;
    color: white;
}
.calc button:active {
    transform: scale(0.98);
    /* Scaling button to 0.98 to its original size */
    box-shadow: 3px 2px 22px 1px rgba(0, 0, 0, 0.24);
    /* Lowering the shadow */
    
}
/* Assignment Listings Page start */

#mainPage{
    background-image: url(../images/keyboard.jpg);
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    height: 350px;

}
#header{
    flex-direction: column;
    background-color: #9b9ea1;
    color: #fff;
    max-width: 50%;
    margin: 0 auto;
    align-self: center;    
}
#header h1{
    margin: 1em;
}
#main div{
    padding: 10px;
    background-color: #9b9ea1;
    margin: 15px;
    width: fit-content;
}
#main a{
    padding: 5px;
    margin: 5px;
    color: #fff;

}


/* Assignment Listings Page  end */

/* assignment 3  */
 section.fcontainer{   
   display: flex;
   flex-wrap: wrap;
   justify-content: space-around; 
   flex-direction: row;    
   align-items: stretch;
   margin: 0 auto;
   max-width: 2600px;
   padding: 10px;
   border: 1 solid black;
}
 section.fcontainer div{
    background-color: blanchedalmond;
    flex-basis: 45%;
    padding: 15px;
    margin: 0 15px;
}
/* Assignment Events. Activity 4. Shape area calculator Start*/
body>div{
    background-color: gray;
    padding: 10px;
    color: #fff;
}

div.formulaImage {
    flex-basis: 33%;
    padding-right: 10px;
}
div.inputForm{
    flex-basis: 33%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-left: 10px;
    margin-right: -10px;
}
.inputForm div{
    padding-bottom: 5px;
    text-align:left;
    
}
.formulaImage img{
    object-fit: cover;
    width: 100%;
    
}
.fcontainer label{
    display: inline-block;
    width: 50%;
   vertical-align: top;
 
    
}
.fcontainer input{
    display: inline-block;
    width: 33%;
    text-align: right;
    height: 1.2em;
    
}
.fcontainer output{
    display: inline-block;
    width: 33%;
    text-align: center;
    
    
}
#buttonRight{
    text-align: end;
    margin-right: 80px;
}
#weeklyWageCalculatorButton{
    margin-left: 19.5em;
}
/* assignment 5 */

div.formulaImage{
    flex-basis: 50%;

}
#assignment5_4{
    justify-content: space-evenly;
}
#inputFields div{
    padding-top: 5px;
}

@media (max-width: 800px) {

    .fcontainer {
        
        flex-direction: column;
    }

    section.fcontainer div {
        flex-basis: 100%;
        margin:15px 15px;
        width: 100%;
    }
    div.inputForm{
        margin-top: 20px;
    }
    div.calc {       
        width: 250px;
    }
    #weeklyWageCalculatorButton{
        margin-left: 0em;
    }
    #mainPage{
        justify-content: center;
    }
    #header{
        max-width: 65%;
    }
    #btn{
        margin: 0;
    }
   
}
#yards{
   margin-right: 0;
}

#error{
    font-size: smaller;
    color: red;
}

/* activity 2, lesson 7 table styles */
table{
    border: 1px solid white;
    border-collapse: collapse;

}
td{ 
    padding: 10px;
    text-align: center;
    border: 1px solid white;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   
    <link rel="stylesheet" href="../css/styles.css">
    <script defer src="./activity2.js"></script>
    <style>
        table{
            border: 1px solid black;
            margin: 0 auto;
        }
        td, th{
            width: 50px;
            height: 50px;
            border: 1px solid black;
        }
        th{
            
            border: 2px solid black;
        }
    </style>
</head>

<body>
   
    <div class="calc" id="assignment6">
        <h2>Multiplication Table</h2>
        <div>
            <label for="number1">Start</label>
            <input type="number" name="number1" id="number1" min="0" placeholder="0" onchange="">
        </div>
        <div>
            <label for="number2">End</label>
            <input type="number" name="number2" id="number2" min="0" placeholder="0" onchange="">
        </div>

        <p id="error"></p>
        <table id="output"></table>
        <p><button id="btn">Calculate</button></p>
    </div>

</body>

</html>

I am having trouble with coding a calculator that asks the user to enter the starting and ending values. The program must use nested for loops. Including row and column labels.

This is what the final table will look like. I will greatly appreciate a link to a relating video or a hint to solve this problem. For example, the output from 1 to 3 might look like this:

    1   2   3
1   1   2   3
2   2   4   6
3   3   6   9

The output from 3 to 5 might look like this:

    3   4   5
3   9  12  15
4  12  16  20
5  15  20  25

The multipliers should appear on top and to the left of the table.

There is one example that I tried to modify for my task.

var result = 'x ';
for (var i = 0; i < 11; i++) {

    for (var j = 0; j < 11; j++) {

        if(i == 0 && j > 0){
          result += '[' + j + ']';
        } 
        else if(j == 0 && i>0){
          result += '[' + i + '] ';
        } 
        else if(i>0 && j>0){
        result += (i*j) + ' ';
        }
    }
    result += '\n'
}

console.log(result);

Output:

x [1][2][3][4][5][6][7][8][9][10]

[1] 1 2 3 4 5 6 7 8 9 10 

[2] 2 4 6 8 10 12 14 16 18 20 

[3] 3 6 9 12 15 18 21 24 27 30 

[4] 4 8 12 16 20 24 28 32 36 40 

[5] 5 10 15 20 25 30 35 40 45 50 

[6] 6 12 18 24 30 36 42 48 54 60 

[7] 7 14 21 28 35 42 49 56 63 70 

[8] 8 16 24 32 40 48 56 64 72 80 

[9] 9 18 27 36 45 54 63 72 81 90 

[10] 10 20 30 40 50 60 70 80 90 100 

I noticed the multipliers are in brackets and the X appears in the top left corner. Is it achieved by using if statements? In my assignment, there must be an empty cell instead of the X. This is what I came up with:

let result = "x";
for(let row = number1; row <= number2; row++){
     result += row + "<tr>";
        
   for( let column = number1; column <= number2; column++){
       result += "<td>" + row * column +"</td>";            
    }
        result += "<br>"
     result += "</tr>"
 }
  document.getElementById("output").innerHTML = result;
}

My program generates a testing table with a start value equal to 2 and an end value equal to 5, and looks like this:

x 4 6 8 10

6 9 12 15

8 12 16 20

10 15 20 25

It is clear that some logic in the formula within the code isn't right.
I am attempting to use a document.getElementById() to output the result table. That is one of the requirements. Having some comments explaining the use of table element tags is greatly appreciated.
The program must take start and end values, not just from 1 to 10.

I appreciate everyone's answers. Some comments within the code that explain what does what and what I am doing wrong are also welcome.

p.s.
I made some corrections to my code. Now it displays ok. One thing is not right. It starts calculation with a number greater than the start number by 1 (eg for input values 2 to 6 it will display 3 to 6). Any ideas?

function displayExpressions(){
    let number1 = getNumber();
    // console.log(number1)
    let number2 = getExpressionsNumber();
    // console.log(number2)
    if (number1 ==0 || number2 == 0){
        document.getElementById("error").innerText =  "Enter a number!" 
    }
    else{
    let result = " "
    for(let row = number1; row <= number2; row++) {
         result += "<tr>";            
       for( let column = number1; column <= number2; column++){           
           if( row == number1 && column > number1){
               result +=  "<th>" + column + "</th>";
           }
           else if(column == number1 && row > number1){
               result += "<th>" + row + "</th>";
           }
           else if (row == number1 && column == number1){
               result =  "<td>" + "x" + "</td>";
           }
           else{
             result += "<td>" + row * column +"</td>";
             document.getElementById("output").innerHTML = result;
           }
       }           
         result += "</tr>";      
     }
      document.getElementById("output").innerHTML = result;
     }
}  

I thank everyone who helped. Here is a working example.

'use strict';

window.addEventListener('load', function () {
  document.getElementById('number1').addEventListener('focus', inputFocus);
  document.getElementById('number2').addEventListener('focus', inputFocus);
  document.getElementById('btn').addEventListener('click', main);
  document.getElementById('number1').focus();
});
function inputFocus() {
  document.activeElement.select();
  document.getElementById('error').innerText =
    'Enter ' + document.activeElement.id + ' value.';
}
function getNumber() {
  let multiplier = document.getElementById('number1').value;
  multiplier = Number(multiplier);
  return multiplier;
}
function getExpressionsNumber() {
  let expressionsNumber = document.getElementById('number2').value;
  expressionsNumber = Number(expressionsNumber);
  return expressionsNumber;
}
// I have a good feeling that checkInput() does not work at all and is most likely redundant.
function checkInput() {
  let number = document.activeElement.value;
  console.log(number);
  if (isNaN(number) || number.trim().lenght == 0) {
    document.getElementById('error').innerText = 'Enter a number!';
    return false;
  }
  return true;
}
function main() {
  console.log('Main is called...'); // testing to see if this function is being called.
  console.log(checkInput()); // testing if this function returns true...
  if (checkInput()) {
    document.getElementById('error').innerText = ''; // set the error message to emptry string... good.
    displayExpressions(); // call the function to display the output...
  }
}

function multiplication(number, expressionsNumber) {
  let result = number * expressionsNumber;
  return result;
}

function displayExpressions(){
    let number1 = getNumber();
    // console.log(number1)
    let number2 = getExpressionsNumber();
    // console.log(number2)
    if (number1 <=0 || number2 <= 0){
        document.getElementById("error").innerText =  "Enter a natural number!" 
    }
    else if(number1 >= number2 ){
        document.getElementById("error").innerText =  "End value must be grater than Start value!" 
    }
    else{
    let result = " "
    for(let row = number1; row <= number2 + 1; row++) {
         result += "<tr>";            
       for( let column = number1; column <= number2 + 1; column++){           
           if( row == number1 && column > number1){
               result +=  "<th>" + (column-1) + "</th>";
           }
           else if(column == number1 && row > number1){
               result += "<th>" + (row - 1) + "</th>";
           }
           else if (row == number1 && column == number1){
               result =  "<th>" + "x" + "</th>";
           }
           else{
           result += "<td>" + (row - 1) * (column-1) +"</td>";
               document.getElementById("output").innerHTML = result;
           }
       }           
         result += "</tr>";      
     }
      document.getElementById("output").innerHTML = result;
    }
}  
  
   
*{
    box-sizing: border-box;
}

.fcontainer{
    display: flex;
}   

div.fcontainer{
    justify-content: space-between;
    flex-basis: 50%;
    margin: 15px;
    
}

body {
    margin: 40px;
    background-color: rgb(230, 255, 247);
    font-family: 'Roboto', sans-serif;
    font-size: calc(10px + (24 - 10) * (100vw - 300px) / (1600 - 300));
}

h1, h2 {
    text-align: center;
}

img {
    display: block;
    width: 300px;
    margin: 0 auto;
}

a {
    text-decoration: none;
}

p {
    margin: 10px 0px;
}

button {
    margin: 10px 0px;
}

div.calc {
    margin: 0 auto;
    display: block;
    width: 600px;
    background-color: rgb(33, 209, 150);
    padding: 20px;
    border-radius: 5px;
    text-align: center;

}


div.calc p {
    text-align: left;
    margin-left: 55px;
}

.calc input {
    width: 80%;
    text-align: right;
    border-radius: 3px;
    border: none;
}

div.cal h2,
 h3 {
    text-align: center;
}
#assignment6 div{
    margin-top: 10px;
}

div.calc div input,
div.calc div label{
    width: 45%;
display: inline-block;
text-align: right;



}

.calc button {
    margin-left: 355px;
    border-radius: 5px;
    border:2px solid #008CBA;
    color: black;
    padding: 16px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    transition-duration: 0.4s;
    cursor: pointer;
}

.calc button:hover {
    background-color: #008CBA;
    color: white;
}
.calc button:active {
    transform: scale(0.98);
    /* Scaling button to 0.98 to its original size */
    box-shadow: 3px 2px 22px 1px rgba(0, 0, 0, 0.24);
    /* Lowering the shadow */
    
}
/* Assignment Listings Page start */

#mainPage{
    background-image: url(../images/keyboard.jpg);
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    height: 350px;

}
#header{
    flex-direction: column;
    background-color: #9b9ea1;
    color: #fff;
    max-width: 50%;
    margin: 0 auto;
    align-self: center;    
}
#header h1{
    margin: 1em;
}
#main div{
    padding: 10px;
    background-color: #9b9ea1;
    margin: 15px;
    width: fit-content;
}
#main a{
    padding: 5px;
    margin: 5px;
    color: #fff;

}


/* Assignment Listings Page  end */

/* assignment 3  */
 section.fcontainer{   
   display: flex;
   flex-wrap: wrap;
   justify-content: space-around; 
   flex-direction: row;    
   align-items: stretch;
   margin: 0 auto;
   max-width: 2600px;
   padding: 10px;
   border: 1 solid black;
}
 section.fcontainer div{
    background-color: blanchedalmond;
    flex-basis: 45%;
    padding: 15px;
    margin: 0 15px;
}
/* Assignment Events. Activity 4. Shape area calculator Start*/
body>div{
    background-color: gray;
    padding: 10px;
    color: #fff;
}

div.formulaImage {
    flex-basis: 33%;
    padding-right: 10px;
}
div.inputForm{
    flex-basis: 33%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-left: 10px;
    margin-right: -10px;
}
.inputForm div{
    padding-bottom: 5px;
    text-align:left;
    
}
.formulaImage img{
    object-fit: cover;
    width: 100%;
    
}
.fcontainer label{
    display: inline-block;
    width: 50%;
   vertical-align: top;
 
    
}
.fcontainer input{
    display: inline-block;
    width: 33%;
    text-align: right;
    height: 1.2em;
    
}
.fcontainer output{
    display: inline-block;
    width: 33%;
    text-align: center;
    
    
}
#buttonRight{
    text-align: end;
    margin-right: 80px;
}
#weeklyWageCalculatorButton{
    margin-left: 19.5em;
}
/* assignment 5 */

div.formulaImage{
    flex-basis: 50%;

}
#assignment5_4{
    justify-content: space-evenly;
}
#inputFields div{
    padding-top: 5px;
}

@media (max-width: 800px) {

    .fcontainer {
        
        flex-direction: column;
    }

    section.fcontainer div {
        flex-basis: 100%;
        margin:15px 15px;
        width: 100%;
    }
    div.inputForm{
        margin-top: 20px;
    }
    div.calc {       
        width: 250px;
    }
    #weeklyWageCalculatorButton{
        margin-left: 0em;
    }
    #mainPage{
        justify-content: center;
    }
    #header{
        max-width: 65%;
    }
    #btn{
        margin: 0;
    }
   
}
#yards{
   margin-right: 0;
}

#error{
    font-size: smaller;
    color: red;
}

/* activity 2, lesson 7 table styles */
table{
    border: 1px solid white;
    border-collapse: collapse;

}
td{ 
    padding: 10px;
    text-align: center;
    border: 1px solid white;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   
    <link rel="stylesheet" href="../css/styles.css">
    <script defer src="./activity2.js"></script>
    <style>
        table{
            border: 1px solid black;
            margin: 0 auto;
        }
        td, th{
            width: 50px;
            height: 50px;
            border: 1px solid black;
        }
        th{
            
            border: 2px solid black;
        }
    </style>
</head>

<body>
   
    <div class="calc" id="assignment6">
        <h2>Multiplication Table</h2>
        <div>
            <label for="number1">Start</label>
            <input type="number" name="number1" id="number1" min="0" placeholder="0" onchange="">
        </div>
        <div>
            <label for="number2">End</label>
            <input type="number" name="number2" id="number2" min="0" placeholder="0" onchange="">
        </div>

        <p id="error"></p>
        <table id="output"></table>
        <p><button id="btn">Calculate</button></p>
    </div>

</body>

</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

黎夕旧梦 2025-01-23 23:12:40

如果您正在构建表格,那么使用“.insertRow”和“.insertCell”会容易得多

function buildit(number1, number2) {
  let tbody = document.querySelector('tbody');
  let result = '';
  let row = tbody.insertRow();
  row.insertCell().textContent = 'X';
  for (let y = number1; y <= number2; y++) {
    // first Row, add the "X" numbers
    if (y === number1) {
      for (let x = number1; x <= number2; x++) {
        row.insertCell().textContent = x;
      }
    }
    // create new Row
    row = tbody.insertRow();
    // and add the "Y" number first
    row.insertCell().textContent = y;
    for (let x = number1; x <= number2; x++) {
      row.insertCell().textContent = x * y;
    }
  }
}
buildit(3, 6);
th,
td {
  text-align: right;
}

tbody tr:first-child,
tbody tr td:first-child {
  color:red;
}
<table>
  <tbody>
  </tbody>
</table>

if you are building a table, then this is MUCH easier with ".insertRow" and ".insertCell"

function buildit(number1, number2) {
  let tbody = document.querySelector('tbody');
  let result = '';
  let row = tbody.insertRow();
  row.insertCell().textContent = 'X';
  for (let y = number1; y <= number2; y++) {
    // first Row, add the "X" numbers
    if (y === number1) {
      for (let x = number1; x <= number2; x++) {
        row.insertCell().textContent = x;
      }
    }
    // create new Row
    row = tbody.insertRow();
    // and add the "Y" number first
    row.insertCell().textContent = y;
    for (let x = number1; x <= number2; x++) {
      row.insertCell().textContent = x * y;
    }
  }
}
buildit(3, 6);
th,
td {
  text-align: right;
}

tbody tr:first-child,
tbody tr td:first-child {
  color:red;
}
<table>
  <tbody>
  </tbody>
</table>

感情洁癖 2025-01-23 23:12:40

尽管该示例可以处理不同的维度,但为了简单起见,我们在本说明中制作了一个 10 x 10 的表格。

  • 使用 2 个 for 循环 - 外部循环生成一行,然后内部循环生成 10 个单元格。
  • 请注意,循环从 0 索引开始,因此迭代次数为 10+1 以进行补偿。
  • 每个单元格内部是当前行索引和当前单元格索引的乘积。
  • 如果行和单元格索引的乘积为 0,则不会生成任何单元格。
  • 当该行有 10 个单元格后,返回外循环并开始下一行。
  • 重复此过程,直到有 10 行。

详细信息在下面的示例中注释

// Reference the <table>
const table = document.querySelector('table');

/**
 * Renders a given htmlString to a 
 * given DOM object.
 * @param {object<DOM>} node - The tag
 * to render HTML to
 * @param {string<HTML>} html - The string
 * that will be rendered as HTML
 */
const xHTML = (node, html) => {
  node.insertAdjacentHTML('beforeEnd', html);
};

/**
 * Renders a table with a given number
 * of rows and columns. Each cell's 
 * contents are a product of row and
 * column indexes.
 * @param {number} rQty - Number of rows
 * @param {number} cQty - Number of columns
 */
const mTable = (rQty, cQty) => {
  // Make one <tr>...
  for (let r = 0; r < rQty + 1; r++) {
    xHTML(table, `<tr></tr>`);
    /*
    If the product of r and c is 0 ?
    make nothing :
    otherwise make a <td>(r x c)</td>
    */ // Do this >cQty< times
    for (let c = 0; c < cQty + 1; c++) {
      let cell = r * c === 0 ? '' : `<td>${r*c}</td>`;
      xHTML(table.rows[r], cell);
    }
    /* Once there is >cQty< cells in 
       row, go to the outer loop to
       make next row and so on */
  }
};

mTable(10, 10);
html {
  font: 2ch/1 Consolas
}

table {
  table-layout: fixed;
  border-collapse: collapse;
}

td {
  width: 10%;
  border: 0.5px solid #000;
  text-align: center
}
<table></table>

Although the example can handle different dimensions, for the sake of simplicity we are making a 10 x 10 table in this explanation.

  • Use 2 for loops -- the outer loop makes one row then the inner loop makes 10 cells.
  • Note that the loops start at 0 index so the iterations are at 10+1 to compensate.
  • Inside of each cell is the product of the current row index and the current cell index.
  • If the product of row and cell index is 0 then no cell is made.
  • Go back to the outer loop once the row has 10 cells and start the next row.
  • Repeat this process until there are 10 rows.

Details are commented in example below

// Reference the <table>
const table = document.querySelector('table');

/**
 * Renders a given htmlString to a 
 * given DOM object.
 * @param {object<DOM>} node - The tag
 * to render HTML to
 * @param {string<HTML>} html - The string
 * that will be rendered as HTML
 */
const xHTML = (node, html) => {
  node.insertAdjacentHTML('beforeEnd', html);
};

/**
 * Renders a table with a given number
 * of rows and columns. Each cell's 
 * contents are a product of row and
 * column indexes.
 * @param {number} rQty - Number of rows
 * @param {number} cQty - Number of columns
 */
const mTable = (rQty, cQty) => {
  // Make one <tr>...
  for (let r = 0; r < rQty + 1; r++) {
    xHTML(table, `<tr></tr>`);
    /*
    If the product of r and c is 0 ?
    make nothing :
    otherwise make a <td>(r x c)</td>
    */ // Do this >cQty< times
    for (let c = 0; c < cQty + 1; c++) {
      let cell = r * c === 0 ? '' : `<td>${r*c}</td>`;
      xHTML(table.rows[r], cell);
    }
    /* Once there is >cQty< cells in 
       row, go to the outer loop to
       make next row and so on */
  }
};

mTable(10, 10);
html {
  font: 2ch/1 Consolas
}

table {
  table-layout: fixed;
  border-collapse: collapse;
}

td {
  width: 10%;
  border: 0.5px solid #000;
  text-align: center
}
<table></table>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文