[英]How do I get the last element child for every item in an array and then show them if they are clicked on
So currently with this code with an onclick I am able to open the sub-menu items. 因此,当前使用带有onclick的代码,我可以打开子菜单项。
The issue is when I click on one of the items to drop down the menu they all open, but I only want the ones I click on to open not all of them. 问题是,当我单击其中一个项目以下拉菜单时,它们全部打开,但是我只希望单击的项目不能全部打开。
function myDropdown() {
var arr = Array.from(document.getElementsByClassName('sub-menu-wrap'));
for (let el of arr) {
var x = el.lastElementChild;
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
}
If you go here https://staging.information-age.com/ and look at the third menu with the icon on the right, this is the menu I am working on so you can get a better understanding of what I mean. 如果您访问https://staging.information-age.com/并查看右侧带有图标的第三个菜单,则这是我正在使用的菜单,以便您可以更好地理解我的意思。
And to add this menu is being generated dynamically by Wordpress using the wp_nav_menu
function. 并且要添加此菜单,是由Wordpress使用
wp_nav_menu
函数动态生成的。
Hope someone can help! 希望有人能帮忙!
The onclick handler should be something along the lines of onclick处理程序应类似于
let all = Array.from(document.getElementsByClassName('sub-menu-wrap'));
// current or "this" if you use onclick, 2 is the offset of the clicked menu item, just for testing
let current = all[2]; // change all[2] to this
for (let el of all) {
el.querySelector(".sub-menu").style.display = (el === current ? "block" : "none");
}
So your problem is, imo, that you probably shouldn't be deciding the click function in the html like that. 因此,您的问题是imo,您可能不应该这样决定html中的click函数。
It looks to me like the site already has jQuery installed on it, so why don't you use that to make things simpler? 在我看来,该网站上已经安装了jQuery,那么为什么不使用它来简化事情呢? You want to assign a click to the
<i>
elements like this: 您想为
<i>
元素分配一个点击,如下所示:
$('#ib-menu i').click(function() { /* do your work in here*/ });
Inside the function, this
is the currently clicked element, and $(this)
is the jQuery-selected version of that element. 在函数内部,
this
是当前单击的元素,而$(this)
是该元素在jQuery中选择的版本。 You can use jQuery to add and remove classes, and add and remove styles, and find elements that are the parent or children of the element you've selected. 您可以使用jQuery添加和删除类,添加和删除样式以及查找作为所选元素的父元素或子元素的元素。
For example, if you want to find the 'sub-menu-wrap' that is the parent of the currently selected element, inside the function you would write var subMenu = $(this).closest('.sub-menu-wrap')
and then, from there, you can check and modify styles and classes 例如,如果要查找当前选定元素的父级的“ sub-menu-wrap”,则可以在函数内部编写
var subMenu = $(this).closest('.sub-menu-wrap')
,然后从那里可以检查和修改样式和类
jQuery will make your life loads easier. jQuery将使您的生活更加轻松。 Every question you have will have a million answers across the internet already as well.
您所遇到的每个问题也将在互联网上得到一百万个答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.