繁体   English   中英

如何更改一个元素更改而又不影响同一类的其他元素?

[英]How do I change one element change without affecting other elements with the same class?

<div class="hello 1">text</div>
<div class="hello 2">other text</div>

我基本上是在尝试使$('.hello').hasClass('.1') “红色”时,使“文本” $('.hello').hasClass('.1')红色。

只需按两个类别进行选择:

$(".hello.1").css("color", "red");

请注意,选择器在第二个点之前没有空格-如果选择了,它将在寻找第二类的元素,而第二类是第一类元素的后代。

或者,如果您要说的是,当单击“ hello”元素时仅当元素具有“ 1”类时,才希望将其变为红色。

$("hello").click(function() {
  var $this = $(this);
  if ($this.hasClass("1"))
    $this.css("color", "red");
});

的CSS

.helloRed {
        color: red;
    }

JS:

$(".hello.1").addClass('helloRed');
$(".hello.1").removeClass('helloRed');

这也可以工作:

$('.1').css('color', 'red');

但是,我确定你知道,

'1'是一个糟糕的类名

$(function() {
 $('.hello').on('click', function() {
   $('.hello:eq(0)').css('color', 'red');

   $('.hello:first').css('color', 'red');

   $('.hello:first-child').css('color', 'red');

   $('.hello:not(:gt(0))').css('color', 'red');

   $('.hello:not(:last)').css('color', 'red');

   $('.hello:not(:not(:not(:not(.1)))):not(.2)').css('color', 'red');
 });
});

或切换红色:

的CSS

.reddy-freddy {
  color: red;
}

js

$('.hello:first').click(function(){$(this).toggleClass('reddy-freddy')});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM