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

时间:2014-12-12 20:29:06

标签: jquery html class

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

我基本上试图制作&#34; text&#34;如果$('.hello').hasClass('.1')没有制作其他文字,则点击时会显示红色&#39;红色。

3 个答案:

答案 0 :(得分:4)

只需按两个类选择:

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

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

或者,如果您说当单击“hello”元素时,您想要将 元素变为红色,只有它具有“1”类,然后:

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

答案 1 :(得分:0)

CSS

.helloRed {
        color: red;
    }

JS:

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

答案 2 :(得分:0)

这也有效:

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

但是,我确定你知道,

&#39; 1&#39;是一个可怕的班级名称

$(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')});
相关问题