gpt4 book ai didi

javascript - 试图在 jQuery 中查找 td 元素的表行的索引

转载 作者:行者123 更新时间:2023-11-30 15:28:47 25 4
gpt4 key购买 nike

我正在尝试从 jQuery 中的 td 元素获取表 rowIndex。这就是我正在尝试的:

var element = $('td').filter(function() { 
var Text = $(this).contents()[0].textContent.trim();
return parseInt(Text, 10) == some_Textvar;
});
var parent = element.parentNode;
var index = parent.rowIndex;

我收到以下错误

Uncaught TypeError: Cannot read property 'rowIndex' of undefined(…)

html:

<div class="class1">
<table class="class2">
<tbody>
<tr>
<td>
</td>
</tr>
<tr>
......

该元素肯定存在,因为我在其余代码中使用它。我怎样才能得到这个 td 元素所在的行?

谢谢

最佳答案

element 是 jQuery 对象,它没有 parentNode 属性,因此它是 undefined,所以会出现错误。

使用.get()/[0] 获取底层 DOM 元素的引用,然后您可以访问该属性。

Retrieve the DOM elements matched by the jQuery object.

var parent = element.get(0).parentNode;
var index = parent.rowIndex;

作为替代方案,使用 jQuery,您可以使用 .index()

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements

var index = element.parent().index();

关于javascript - 试图在 jQuery 中查找 td 元素的表行的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42554420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com