如何使用$(this)重复使用的元素只触发单击的元素
问题描述:
我想让我的JS逻辑使用$(this),所以我可以重用我的代码在多个元素相同的页面,以便它们分别触发。
这是我的JS代码:
$(".fab").on("click", function(){
$(this).toggleClass("clicked");
$(".screen2").addClass("active");
$(".box2 ,.box1 ,.box3").addClass("active");
});
$("#close").on("click", function(){
$(".screen2").removeClass("active");
$(".fab").removeClass("clicked");
$(".box1 ,.box2 ,.box3").removeClass("active");
});
我的HTML:
<div class="app">
<div class="header"></div>
<div class="content">
<h1>Click the fab</h1>
</div>
<div class="fab"></div>
<div class="screen2">
<h1>new window</h1>
<div id="close"></div>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
</div>
我该如何使用正确的$(这)?我想要做的就是让JS代码可以在同一页面中重复使用多个元素,以便它只触发单击.fab按钮的元素...
答
您还需要使用$(this), .prev(), .next(), .find(), .closest()
等来遍历DOM来引用正在处理的元素附近的元素,否则它将定位到文档中的所有类。
$(".fab").on("click", function(){
$(this).toggleClass("clicked");
$(this).next(".screen2").addClass("active");
$(this).next(".screen2").find(".box2 ,.box1 ,.box3").addClass("active");
});
$("#close").on("click", function(){
$(this).closest(".screen2").removeClass("active");
$(this).closest(".screen2").prev(".fab").removeClass("clicked");
$(this).closest(".screen2").find(".box1 ,.box2 ,.box3").removeClass("active");
});
答
可以存储jQuery选择在一个数组,遍历它,并为阵列中的每个jQuery选择,使用jQuery的.each()
通过其内部元件进行迭代。
在以下示例中,例如,在DOM中可能有多个class1
实例。
var arrElements = [$('#id1'), $('#id2'), $('.class1')];
for (var i = 0; i < arrElements.length; i++) {
arrElements[i].each(function() {
$(this).on('click', function() {
// do stuff (use $(this) to refer to the current object)
});
})
}
没有比使用所有那些.next和最接近的更好的方法吗?只是看起来如此冗长...... – user2513846
如果你的元素具有唯一的标识符,如ID和ID,那么是的。否则,你必须向JavaScript描述如何找到你想要的特定元素。 – j08691
但具有唯一标识符,如ID,则不再可以在页面中包含该HTML块的多个实例... – user2513846