[英]how to write this code in right way in javascript
$("#wedding").click(function() {
$(".wedding, .wedding div").addClass("menuclick");
$(".homecoming div, .ourstory div, .weddingcrew div").removeClass("menuclick");
});
$("#homecoming").click(function() {
$(".homecoming, .homecoming div").addClass("menuclick");
$(".wedding div, .ourstory div, .weddingcrew div").removeClass("menuclick");
});
$("#ourstory").click(function() {
$(".ourstory, .ourstory div").addClass("menuclick");
$(".wedding div, .homecoming div, .weddingcrew div").removeClass("menuclick");
});
$("#weddingcrew").click(function() {
$(".weddingcrew, .weddingcrew div").addClass("menuclick");
$(".wedding div, .ourstory div, .homecoming div").removeClass("menuclick");
});
i wrote this code for animate css animation.there's four items, and when i click one one item is animate and others will return. 我为动画css动画编写了此代码。有四个项目,当我单击一个项目时,一个项目就是动画,其他项目将返回。 i need to know how to simplify this code.
我需要知道如何简化此代码。
Without changing your html, you could do this: 在不更改HTML的情况下,您可以执行以下操作:
$("#wedding, #homecoming, #ourstory, #weddingcrew").click(function() {
// remove menuclick class from all elements that currently have it
$(".menuclick").removeClass("menuclick");
// now add menuclick just to elements associated with the clicked item
$("." + this.id).find("div").andSelf().addClass("menuclick");
});
This depends on the fact that your element ids are exactly the same as the corresponding classes on the elements they're associated with. 这取决于您的元素ID与与其关联的元素上的相应类完全相同的事实。
If you could add a common class, say class="menu"
to the #wedding, #homecoming
, etc. items then you could simplify the initial selector to $(".menu")
. 如果您可以向
#wedding, #homecoming
添加通用类,例如class="menu"
,则可以将初始选择器简化为$(".menu")
。
PS If you're using jQuery v1.8 or later use .addBack()
instead of .andSelf()
. PS如果您使用的是jQuery v1.8或更高版本,请使用
.addBack()
而不是.andSelf()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.