gpt4 book ai didi

javascript - jquery newb,难以理解选择器和索引

转载 作者:行者123 更新时间:2023-11-28 00:13:12 25 4
gpt4 key购买 nike

我在理解选择器和索引在 JQuery 中的工作方式时遇到一些问题。我希望编写一些基于类属性操作 html 元素的函数,我意识到当我尝试使用 index() 方法或 prevAll().length 来获取元素在一组元素中的位置时,我并不总能得到预期的结果。

下面,我有一段 jquery 代码,它对 .element_list 类的所有内容执行某些操作,然后在该代码中对 .element_list_item 类的所有内容执行操作。我有两个 .element_lists,A 和 B,所有这一切都是提醒我 .element_list_items 的索引。对于列表 A,索引返回为 0 和 1,如预期的那样。在列表 B 中,我添加了一个没有类属性的 thead 元素,所以在我看来它不应该被我的 jquery 代码获取,但是两个 .element_list_items 返回时的索引为 1 和 2,而不是预期的 0 和 1 .

这是为什么呢?我的选择器正在寻找具有类 .element_list_item 和等于包含 .element_list ID 的类的元素,那么为什么添加 thead 会影响 tbodies 的位置?

感谢任何帮助理解这一点。

<script language="javascript" type="text/javascript">
$(document).ready(function ()
{
$('.element_list').each(function()
{
var list_id = $(this).attr('id');
var first_item_id = $(this).find('.' + list_id + '.element_list_item:eq(0)').attr('id');

alert('List and first list item: ' + list_id + ' - ' + first_item_id);

$(this).find('.' + list_id + '.element_list_item').each(function()
{
var list_item_id = $(this).attr('id');
var index = $(this).prevAll().length;

alert('List item and its index: ' + list_item_id + ' - ' + index);
});
});
});
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="" enableviewstate="true">
<br />
<br />
<table class="table_noborder">
<thead>
<tr>
<td>List A</td>
</tr>
</thead>
<tbody id="list_A" class="element_list">
<tr>
<td>
<table>
<tbody id="list_A_item0" class="element_list_item list_A">
<tr>
<td>First Item</td>
</tr>
</tbody>
<tbody id="list_A_item1" class="element_list_item list_A">
<tr>
<td>Second Item</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>

<table>
<thead>
<tr>
<td>List B</td>
</tr>
</thead>
<tbody id="list_B" class="element_list">
<tr>
<td>
<table>
<thead>
<tr>
<td>Header</td>
</tr>
</thead>
<tbody id="list_B_item0" class="element_list_item list_B">
<tr>
<td>First Item</td>
</tr>
</tbody>
<tbody id="list_B_item1" class="element_list_item list_B">
<tr>
<td>Second Item</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

最佳答案

使用 .index()与所有 sibling 相比,没有参数将获得它的索引。您可以将选择器传递给它以检查与集合的比较

所以

$('#list_B_item0').index() // will return 1 since thead(it's prev sibling) is in index 0

但是

$('#list_B_item0').index('.element_list_item.list_B') //  returns 0 since it will compare it's index with the collection

反之亦然

$('.element_list_item.list_B').index('#list_B_item0') // returns 0

关于javascript - jquery newb,难以理解选择器和索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13979668/

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