javascript - 如何从 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。
解决方案
我希望这就是你所需要的:
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>
推荐阅读
- java - 最多旋转 2 张卡片
- javascript - 您可以在仍然打字的同时在文本区域中按下标签而不改变焦点吗?
- mysql - mysql工作台选择并选择问题
- mysql - 如何在mysql中声明变量并将其值设置为计数结果
- python - Python 2.7 - 带有来自 pyodbc 的数据的 Pandas UnicodeEncodeError
- jdbc - 使用带有可调用语句的 JMETER GUI JDBC 请求——我如何获取结果集/元数据?
- excel - 将范围复制到另一个工作簿时下标超出范围
- ffmpeg - FFMPEG NVENC HEVC 转 H264
- gcc - 更改 gcc/g++ abi 中的调用约定
- sql - 参数。添加忽略参数在字符串中的位置