如何使用 jQuery 根据表达式检查当前选择?
jqueryweb developmentfront end technology
概述
jQuery 是一个快速、小巧且功能丰富的 JavaScript 库。它支持 DOM 操作、事件处理、动画、CSS 和 Ajax。为了实现此需求,我们将使用 jQuery 的 "is(selector)" 方法。
is(selector)
此方法根据表达式/选择器检查当前选定的元素,如果任何选定元素与选择器匹配,则返回 true。
在下面的代码中,我们创建了一个类名为"test"的容器。我们希望在点击容器时更改其背景颜色。因此,容器的类名"test"将用作选择器,并在每次点击容器时对其进行检查。如果匹配,则容器的背景颜色将被更新。
<div class="test">Let's learn!</div>
<div>Second Container</div>
<script>
$("div").on("click", function () {
if ($(this).is(".test")) {
$(this).css({
background: "grey",
});
}
})
</script>
在这里,我们将创建一个基本的 HTML 页面,其中包含一些具有不同类的容器 (div)。我们将添加一个脚本 (<script>) 标签,并在其中创建一个函数,当点击任意容器时,该函数都会被触发。它将检查容器的类名并执行相应的操作。
示例
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<style>
div {
padding: 10px;
}
</style>
<h3>
Let's change the CSS of container w.r.t class using jQuery's is(selector) method.
</h3>
<div class="blue">Change the background to blue</div>
<div class="green">Change the background to green</div>
<div class="red">Change the background to red</div>
<div class="blue">Change the background to blue</div>
<div class="green">Change the background to green</div>
<div class="red">Change the background to red</div>
<!-- Script tag to embed jquery -->
<script>
$(document).ready(function () {
$("div").on("click", function () {
if ($(this).is(".blue")) {
$(this).css({
color: "white",
background: "blue",
});
} else if ($(this).is(".green")) {
$(this).css({
color: "white",
background: "green",
});
} else if ($(this).is(".red")) {
$(this).css({
color: "white",
background: "red",
});
}
});
});
</script>
</body>
</html>
当选择"绿色"/"红色"/"蓝色"类的容器时,容器的背景颜色将分别更改为绿色/红色/蓝色。
说明
未选择任何内容时。
选择"绿色"类的容器时
选择"红色"类的容器时
选择所有容器时

