jquery:不选择不排除预期元素

问题描述 投票:2回答:5

鉴于以下内容:

// all text should be red except in the excludeme id
$('body:not(#excludeme)').css('color', 'red');
// $('#excludeme').css('color','blue');
body {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
	div text
</div>
<br />
<span>
	<a id="excludeme">this text should be green</a>
	<br />
	span text
</span>

所有文本都显示为红色,但excludeme id中的文本应保持为绿色。为什么:not selector不排除所选的id?

jquery
5个回答
1
投票

:not按预期工作。如果您检查html代码,您可以看到a元素没有将颜色更改为红色的内联样式。它从父元素获取颜色,因为所有其他元素都有红色。如果你想要,你可以在css中为这样的元素声明一个样式

#excludeme{
    color: green;
}

您可以在inheritance css中阅读更多关于here的内容


1
投票

当你使用:not()时,颜色将从parent元素继承。

试试以下代码 -

// all text should be red except in the excludeme id
$("#excludeme").css('color', 'green')
$('body').css('color', 'red');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
    <div>
        div text
    </div>
    <br />
    <span>
        <a id="excludeme">this text should be green</a>
        <br />
        span text
    </span>
</body>

或者你也可以尝试这个 -

body{
  color: red;
}

#excludeme{
  color: green;
}
<body>
    <div>
        div text
    </div>
    <br />
    <span>
        <a id="excludeme">this text should be green</a>
        <br />
        span text
    </span>
</body>

0
投票

它继承自body,因为body也没有excludeme id,请参阅:

// all text should be red except in the excludeme id
$('body:not(#excludeme)').css('color', 'red');
//$('#excludeme').css('color','blue');
body {
  color: green;
}
#excludeme {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<body>
  <div>
    div text
  </div>
  <br>
  <span>
<a id="excludeme">this text should be green</a>
<br>
span text
</span>
</body>
a

如果明确指定excludeme的颜色,它将起作用。


0
投票

您的选择器正在选择任何不具有excludeme id的body元素。这只是选择文档的body元素。然后,将该样式应用于该元素,该元素将覆盖您在CSS中应用的样式。

你最终会得到像这样的东西,其中#excludeme元素没有以任何方式成为目标:

<html>
    <head>
        <style>
            body {
                color: green;
            }
        </style>
    </head>

    <body style="color: red">
        ...
        <a id="excludeme">this text should be green</a>
        ...
    </body>
</html>

您需要直接定位该元素以覆盖样式。


0
投票

正如@ TiiJ7建议的那样,检查一下它是否合适,Click Me!!

通过这个改变CSS:

body {
  color: red;
}

和JS这个:

$('#excludeme').css('color', 'green');
© www.soinside.com 2019 - 2024. All rights reserved.