[英]How can I use for loop in jQuery hover
I want to use loops to iterate and apply hover with each element then remove class from another collection of elements.我想使用循环对每个元素进行迭代和应用 hover,然后从另一个元素集合中删除 class。 Tried each function but didn't work.
尝试了每个 function 但没有用。
$("#product").hover(function () { $(".z").removeClass("viz"); $(".arrow1").css("transform", "rotate(180deg)") }, function () { $(".z").addClass("viz"); $(".arrow1").css("transform", "rotate(0deg)") }) $("#company").hover(function () { $(".y").removeClass("viz"); $(".arrow2").css("transform", "rotate(180deg)") }, function () { $(".y").addClass("viz"); $(".arrow2").css("transform", "rotate(0deg)") }) $("#connect").hover(function () { $(".x").removeClass("viz"); $(".arrow3").css("transform", "rotate(180deg)") }, function () { $(".x").addClass("viz"); $(".arrow3").css("transform", "rotate(0deg)") })
You can create an array of the IDs of the elements you want to select and loop through them.您可以创建一个包含您想要的元素的 ID 的数组 select 并循环遍历它们。 like this:
像这样:
let list = ['product', 'company', 'connect'] list.forEach(element => { $("#"+element).hover(function () { $(".z").removeClass("viz"); $(".arrow1").css("transform", "rotate(180deg)") }, function () { $(".z").addClass("viz"); $(".arrow1").css("transform", "rotate(0deg)") }) })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
EDIT: Using jquery selectors, for selecting list items of a ul with id="menu"
is something like this:编辑:使用 jquery 选择器,选择带有
id="menu"
的 ul 的列表项是这样的:
var items = $("ul#menu li");
for (let li of items) {
$(li).hover(function () {
// ...
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.