首页 > 解决方案 > 如何从 HTML 表中仅访问整数值(仅限卷号)并将值存储在 JS 数组中

问题描述

<!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">
   <title>Document</title>
</head>

<body>
   <table border="10px solid ">
      <tr>
         <th>S.No</th>
         <th>First Name</th>
         <th>Last Name</th>
         <th>Roll number</th>
      </tr>
      <tr>
         <td>1</td>
         <td>Hemanth</td>
         <td>Kumar</td>
         <td>3205020</td>
      </tr>
      <tr>
         <td>2</td>
         <td>Manish</td>
         <td>Raj</td>
         <td>3205037</td>
      </tr>
      <tr>
         <td>3</td>
         <td>Dinesh</td>
         <td>Kanth</td>
         <td>3205015</td>
      </tr>
   </table><br>
</body>

</html>

我只需要将卷号存储在 javascript 数组中。我是学习 Javascript 的初学者,所以请帮我解决这个问题。并且还向我推荐任何教程网站来快速学习 JS 和 jQuery。

标签: javascripthtmljquery

解决方案


我希望这就是你所需要的:

var table = document.getElementsByTagName("table")[0];

var myArray = [];

/*
First we get all "tr" elements from the table,
then we need to turn the node list to an array using "Array.from",
then we use the "forEach" function to work with this new array
*/
Array.from(table.getElementsByTagName("tr")).forEach(function(element, index){
  /*
  Using this "if" the code will ignore the first "tr" that are the titles
  0 is recognized as "false" for boolean operation, so any number will get as "true"
  */
  if(index){
    console.log(element.children[0].innerHTML,
                element.children[1].innerHTML,
                element.children[2].innerHTML,
                element.children[3].innerHTML /* <-- this one is the roll number */);
                    
    myArray.push(element.children[3].innerHTML);
    /*
    if you need to store the HTML Element use: .push(element.children[3]);
    The innerHTML propertie returns a string with the HTML text that is inside of an element 
    */
  }
});

    console.log(myArray);
    <!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">
       <title>Document</title>
    </head>

    <body>
       <table border="10px solid ">
          <tr>
             <th>S.No</th>
             <th>First Name</th>
             <th>Last Name</th>
             <th>Roll number</th>
          </tr>
          <tr>
             <td>1</td>
             <td>Hemanth</td>
             <td>Kumar</td>
             <td>3205020</td>
          </tr>
          <tr>
             <td>2</td>
             <td>Manish</td>
             <td>Raj</td>
             <td>3205037</td>
          </tr>
          <tr>
             <td>3</td>
             <td>Dinesh</td>
             <td>Kanth</td>
             <td>3205015</td>
          </tr>
       </table><br>
    </body>


推荐阅读