方法:1、利用index()和parent()方法來獲取當前元素的行位置,語法為“元素對象.parent().index()+1;”;2、利用index()方法來獲取當前元素的列位置,語法為“元素對象.index()+1;”。
本教程操作環(huán)境:windows7系統(tǒng)、jquery3.2.1版本、Dell G3電腦。
jquery怎樣獲取當前元素在第幾行第幾列
我們可以通過index()方法和parent()方法來獲取當前元素在第幾行第幾列,示例如下:
<!DOCTYPE html> <html> <head> <script src="/jquery/jquery-1.11.1.min.js"></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> <script> $(function(){ $("table td").click(function() { var row = $(this).parent().index() + 1; // 行位置 var col = $(this).index() + 1; // 列位置 alert("當前位置:第"+row+"行,第"+col+"列") }); }); </script> </body> </html>
輸出結果:
當點擊其中的一個單元格元素時,輸出結果:
相關視頻教程推薦:jQuery視頻教程