grvData表格:如何正确获取.tabulator-col-title在.tabulator-headers的索引?
Hey there, let's break down why your current code is returning 0 and how to get the correct column index you need.
The Problem with Your Current Code
When you run $(".tabulator-col-title:contains('Rent')").index(), jQuery's index() method (without arguments) returns the position of the element relative to its direct sibling elements. Looking at your HTML structure:
The
.tabulator-col-titleelement sits inside.tabulator-col-title-holder, and its only sibling is.tabulator-col-sorter. So it's the first element in that parent, hence the index 0. But this isn't the column index you're after—you want the position of the entire.tabulator-col(the column container) within.tabulator-headers.
Solution 1: Traverse Up to the Column Container
First, target the .tabulator-col-title with "Rent", then traverse up to its parent .tabulator-col element, then get its index relative to other columns:
$(document).ready(function () { // Find the column container that holds the "Rent" title const rentColumn = $(".tabulator-col-title:contains('Rent')").closest(".tabulator-col"); // Get the index of this column within the headers container alert(rentColumn.index()); // Will return 2 (since indexes start at 0, Rent is the 3rd column) });
Solution 2: Precise Matching to Avoid False Positives
If you have columns like "Total Rent" (which also contains "Rent"), the :contains() selector will match those too. For exact text matching, use this approach instead:
$(document).ready(function () { const columnIndex = $(".tabulator-headers .tabulator-col").index(function() { // Trim text to avoid whitespace issues return $(this).find(".tabulator-col-title").text().trim() === "Rent"; }); alert(columnIndex); // Returns the correct index (2 in your case) });
This method loops through each column container, checks if its title exactly matches "Rent", and returns the index of that column—no false matches, and directly targets the column level you care about.
内容的提问来源于stack exchange,提问作者Taqi Gates

