如何在 jQuery 的选择器中定义类似 OR 的内容?
How can I define something like OR in jQuery's selector?
这是我当前的代码:
$(".close_btn").click(function(e) {
$(".box1").fadeOut(100);
$(".box2").fadeOut(100);
});
如您所见,目前,当您点击.close_btn
时,.box1
和.box2
都会被隐藏。现在我想用 $(this)
和 .closest()
只隐藏一个框 (单击 .close_btn
的父项,有两个 .close_btn
).我的意思是我想要这样的东西:
$(".close_btn").click(function(e) {
$(this).closest(".box1" OR ".box2").fadeOut(100);
});
这样做可行吗?
您可以只使用逗号分隔多个选择器:
$(".close_btn").click(function(e) {
$(this).closest(".box2, .box1").fadeOut(100);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box1">
<button class="close_btn">Close</button>
</div>
<div class="box2">
<button class="close_btn">Close</button>
</div>
这是我当前的代码:
$(".close_btn").click(function(e) {
$(".box1").fadeOut(100);
$(".box2").fadeOut(100);
});
如您所见,目前,当您点击.close_btn
时,.box1
和.box2
都会被隐藏。现在我想用 $(this)
和 .closest()
只隐藏一个框 (单击 .close_btn
的父项,有两个 .close_btn
).我的意思是我想要这样的东西:
$(".close_btn").click(function(e) {
$(this).closest(".box1" OR ".box2").fadeOut(100);
});
这样做可行吗?
您可以只使用逗号分隔多个选择器:
$(".close_btn").click(function(e) {
$(this).closest(".box2, .box1").fadeOut(100);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box1">
<button class="close_btn">Close</button>
</div>
<div class="box2">
<button class="close_btn">Close</button>
</div>