为什么下面的 if 语句没有给我想要的结果。每次它只给我一个黄色的段落,即使相关的词不满足 :contains 表达式。我在下面粘贴查询。
$(document).ready(function() {
if ($("p:contains(x)")) {
$("p").css("background-color", "yellow");
} else {
$("p").css("background-color", "red");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="scripts/jquery-3.2.0.min.js"></script>
<script src="scripts/script.js"></script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>This is a heading</h1>
<p class="hand">This is a paragraph</p>
<p>glow</p>
<p>The heading, paragraph and button element have a click event defined. Click on each element to display which element triggered the event.</p>
<div style="color:blue;"></div>
</body>
</html>
最佳答案
我看不到对变量 x 的引用 - 所以我只是编造了它 :)。下面判断是字符串“glow”在p中,使背景变黄。任何不包含“glow”的 p 都具有红色背景色。但是,我建议添加/删除类而不是直接调整 CSS。
$(document).ready(function(){
$("p:contains('glow')").css("background-color", "yellow");
$("p").not(":contains('glow')").css("background-color", "red");
})
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h1>This is a heading</h1>
<p class="hand">This is a paragraph</p>
<p>glow</p>
<p>The heading, paragraph and button element have a click event defined. Click on each element to display which element triggered the event.</p>
<div style="color:blue;"></div>
</body>
</html>
关于javascript - 查询 jquery if 和 :contains,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42991411/