Home >Web Front-end >JS Tutorial >How to query the tr number of the current element in jquery

How to query the tr number of the current element in jquery

WBOY
WBOYOriginal
2021-12-13 15:12:053759browse

Method: 1. Use the "$(this)" statement and the index() method to obtain the index position of the current tr element, and then obtain the number of the current element. The syntax is "$(this).index( ) 1;"; 2. Use the alert() method to output the obtained current element position number.

How to query the tr number of the current element in jquery

The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.

How does jquery query the tr number of the current element?

We can use the index() method to query the tr number of the current element. tr.

index() method returns the index position of the specified element relative to other specified elements.

These elements can be specified via jQuery selectors or DOM elements.

Note: If the element is not found, index() will return -1.

The example is as follows:

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(function(){
    $("table tr").click(function() {
        var col = $(this).index() + 1; // 列位置
        alert("当前位置:第"+col+"个tr")
    });
}); 
</script>
</head>
<body>
<table id = "test" border="1">
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>2</td><td>4</td><td>5</td><td>6</td></tr>
    <tr><td>3</td><td>7</td><td>8</td><td>9</td></tr>
    <tr><td>4</td><td>1</td><td>2</td><td>3</td></tr>
</table>
</body>
</html>

Output result:

How to query the tr number of the current element in jquery

When you click on the second row of elements, the output result is:

How to query the tr number of the current element in jquery

Recommended related video tutorials: jQuery video tutorial

The above is the detailed content of How to query the tr number of the current element 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