jQuery为除nth-child之外的所有div设置了一个类 [英] jQuery set a class to all divs except nth-child

查看:47
本文介绍了jQuery为除nth-child之外的所有div设置了一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在选择列表中选择第一个元素时,我试图隐藏一个类的所有div,而不是第一个.我以为第4行会覆盖第3行,但它似乎没有以这种方式工作.

Im trying to hide all divs of a class apart from the first one when the first element is selected in a select list. I thought that line 4 would override line 3 but it doesnt appear to be working this way.

function myFunction() {
  if (jQuery('#select').val() == '1') {
    jQuery('.mydiv').addClass('hide');
    jQuery('.mydiv(1)').removeClass('hide');
  }
}

更新-各个div.mydiv可能已经具有hide类,因此代码需要确保只有第一个实例具有该类.其他div需要删除该类.

UPDATE - the various div.mydiv's may already have the hide class, so the code needs to make sure only the 1st instance has the class. The other divs need to have the class removed if they have it.

推荐答案

将其添加到全部,首先过滤,然后删除该类.

Add it to all, filter to first, and remove the class.

function myFunction() {
  if (jQuery('#select').val() == '1') {
    jQuery('.mydiv').addClass('hide').first().removeClass("hide");
  }
}

这篇关于jQuery为除nth-child之外的所有div设置了一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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