8.jQuery遍历索引的方法

# jQuery遍历索引的方法

- 1.each()
```js
$('li').each(function(index, ele){
    $(ele).text(index).addClass('demo' + index);
});
```

- 2.children()
```js
$('ul').children().each(function(index, ele){
    $(ele).text(index).addClass('demo' + index);
});
```

- 3.index() 获取标签在兄弟元素中索引的值
```js
$('ul').on('click', 'li', function(e){
    console.log( $(e.target).index() );
});//获取ul下li的索引值

$('p').children().on('click', function(e){
    console.log( $('p span').index( $(e.target) ) );//找到p元素下所有span元素,并且输出点击的span元素在所有span元素中的索引值
});//获取ul下li的索引值
```

以上是markdown格式的笔记
posted @ 2020-05-14 08:52  lanshanxiao  阅读(455)  评论(0编辑  收藏  举报