JQuery获取相同类名元素的下标索引

1.问题描述

假设有这么一段代码,我该如何获得指定的div,并对其操作?

<div class="xinhao_category"></div>

<div class="xinhao_category"></div>

<div class="xinhao_category"></div>

<div class="xinhao_category"></div>

<div class="xinhao_category"></div>

2.解决方案

通过$(this).index()获取对应元素的下标;

通过siblings()方法可以实现 同级元素 的反选功能;

// 设置点击事件

$('.xinhao_category').on('click', function() {

      $('.xinhao_category:eq(' + $(this).index() + ')').css({'background': 'orange', 'color': 'black'});

      $('.xinhao_category:eq(' + $(this).index() + ')').siblings().css({'background': 'rgba(255, 255, 255, 0.1)', 'color': 'white'});

});

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容