Home >Web Front-end >Front-end Q&A >How to get the current row of table in jquery

How to get the current row of table in jquery

青灯夜游
青灯夜游Original
2022-04-21 17:38:275090browse

Method: 1. Use "$("tr").click(function(){})" to bind the click event to the table row element and set the processing function; 2. In the function, use " $(this).index() 1" just get the row number of the clicked element. The value obtained by index() starts counting from 0 and needs to be incremented by 1.

How to get the current row of table in jquery

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.

jquery gets the current row of the table

Gets the current row of the table (table), you can bind it to the table element Set a click event, which element is clicked, which is the current element; then determine the number of rows of the element.

Implementation idea:

  • Use click() to bind the click event to the table row element tr, and set the event processing function (tr defines the row in the HTML table)

  • In the processing function, use index() to obtain the position of the clicked element and obtain the number of rows of the clicked element.

    Note: The element position obtained by index() is from If the count starts at 0, it needs to be added by 1.

Implementation code:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<style>
			tr:nth-of-type(even) {
				background-color: red;
			}
			tr:nth-of-type(odd) {
				background-color: pink;
			}
		</style>
		<script>
			$(document).ready(function() {
				$("tr").click(function() {
					
					console.log("是表格的第 "+($(this).index()+1)+" 列");
				});
			});
		</script>
	</head>
	<body>
		<table border="1">
			<tr>
				<th>商品</th>
				<th>价格</th>
			</tr>
			<tr>
				<td>T恤</td>
				<td>¥100</td>
			</tr>
			<tr>
				<td>牛仔褂</td>
				<td>¥250</td>
			</tr>
			<tr>
				<td>牛仔库</td>
				<td>¥150</td>
			</tr>
		</table>
		<p>判断点击列是表格的第几列</p>

	</body>
</html>

How to get the current row of table in jquery

Description: The element position obtained by the

index() method is from 0 At the beginning, so if you want to get the accurate number of rows, you need to calculate it and add 1 to the obtained value.

[Recommended learning: jQuery video tutorial, web front-end video]

The above is the detailed content of How to get the current row of table in jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn