jQuery通过其索引查找元素 [英] jQuery find an element by its index

查看:299
本文介绍了jQuery通过其索引查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有选择

<div id="container">
    <div>item 1</div>
    <div>item 2</div>
    <div>item 3</div>
    <div>item 4</div>
</div>

如何通过索引选择div?

How can I select a div by it's index?

例如,我想通过使用索引= 1选择项目2,而不是通过'div'或文本包含项目2"

For example, I'd like to select item 2...by using index = 1, not by 'div' or text contains "item 2"

推荐答案

以下任意一项:

  • .index -这是吸气剂.获取给定元素的索引,并基于该元素应用逻辑.
  • .eq .slice -这些可用于从给定的jQuery集合中获取元素
  • :nth-child -选择一个 n child(!!)元素,分别对应于父元素.
  • .index - This is the getter. Get the index of a given element, and apply logic, based on it.
  • .eq, :eq or .slice- These can be used to get an element from a given jQuery collection
  • :nth-child - Select an element which is the nth child (!!) element, respective to the parent.

根据您的情况,eq:nth-child是合适的.例如:

In your case, eq or :nth-child are suitable. Eg:

var item1 = $('#container > :nth-child(1)');  // parent > child (=first child)
var item2 = $('#container').children().eq(1); // Zero-based indexes

这篇关于jQuery通过其索引查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆