尝试在表中查找名为"客户"的列名的索引结果 -1



尝试使用jQuery/javascript在表中找到名为Customers的列名称的索引,但这总是给我-1

let tableDatacy = "Results_Table";
let columnName = "Customer";
let tableHeaders = [];
tableHeaders = Cypress.$(`[data-cy=${tableDatacy}] > thead:nth-child(0) > tr:contains(${columnName})`);
let columnPosition = tableHeaders.toString().indexOf(columnName);

<table data-cy="Results_Table">
<thead class="HeaderOriginal">
<tr class="tablesorter-headerRow">
<th class="hideExport hidePrint tablesorter-header" data-column="0" tabindex="0" unselectable="on" style="user-select: none;"><div class="tablesorter-header-inner">&nbsp;</div></th>
<th class="ajaxOrder tablesorter-header" order="customer" data-column="3" tabindex="0" unselectable="on" style="user-select: none;">
<div class="tablesorter-header-inner">
<a href="javascript: void(0);" class="desc">Customers</a>
</div>
</th>
<th class="hideExport" data-column="0" tabindex="0" unselectable="on" style="user-select: none;"><div class="tablesorter-header-inner">&nbsp;</div></th>
<th class="ajaxOrder tablesorter-header" order="customer" data-column="3" tabindex="0" unselectable="on" style="user-select: none;">
<div class="tablesorter-header-inner">
<a href="javascript: void(0);" class="desc">Machine</a>
</div>
</th>
</tr>
</thead>
</table>

如果您只想使用jQuery,则等效的是

const index = Cypress.$(`[data-cy="Results_Table"]`)
.find(`th:has(a:contains("Customers"))`)
.index()

注意:在尝试使用jQuery之前,应该先加载页面,例如

beforeEach(() => {
cy.visit(...)
})
it('...', () => {
const index = Cypress.$(`[data-cy="Results_Table"]`)
.find(`th:has(a:contains("Customers"))`)
.index()
...
})

您可以使用invoke('index')来调用列的索引值。你可以从Jquery文档中了解更多。

cy.get('[data-cy="Results_Table"]')
.find(`th:contains('Customers')`)
.invoke('index')
.then((index) => {
cy.log(index); // Will Print 1
});

如果您想在同一测试中稍后使用索引值,您可以使用.as()

cy.get('[data-cy="Results_Table"]')
.find(`th:contains('Customers')`)
.invoke('index')
.as('indexValue')
cy.get('@indexValue').then((indexValue) => {
expect(indexValue).to.eq(1)
//Use the index value here
})

最新更新