如何获得数组中每个项目的最后一个元素子项,然后在单击它们时显示它们 [英] How do I get the last element child for every item in an array and then show them if they are clicked on

查看:79
本文介绍了如何获得数组中每个项目的最后一个元素子项,然后在单击它们时显示它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当前使用此代码并带有onclick,我可以打开子菜单项.

So currently with this code with an onclick I am able to open the sub-menu items.

问题是,当我单击其中一项以下拉菜单时,它们全部打开,但我只希望单击的项不能全部打开.

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";
  }
}
}

如果您在这里 https://staging.information-age.com/并查看在第三个菜单(带有右侧图标)上,这是我正在使用的菜单,以便您可以更好地理解我的意思.

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.

要添加此菜单,是由Wordpress使用wp_nav_menu函数动态生成的.

And to add this menu is being generated dynamically by Wordpress using the wp_nav_menu function.

希望有人可以提供帮助!

Hope someone can help!

推荐答案

因此,您的问题是imo,您可能不应该这样决定html中的click函数.

So your problem is, imo, that you probably shouldn't be deciding the click function in the html like that.

在我看来,该网站上已经安装了jQuery,那么为什么不使用它来简化事情呢?您想为<i>元素分配一个点击,如下所示:

It looks to me like the site already has jQuery installed on it, so why don't you use that to make things simpler? You want to assign a click to the <i> elements like this:

$('#ib-menu i').click(function() { /* do your work in here*/ });

在函数内部,this是当前单击的元素,而$(this)是该元素的jQuery选择版本.您可以使用jQuery添加和删除类,添加和删除样式,以及查找作为所选元素的父元素或子元素的元素.

Inside the function, this is the currently clicked element, and $(this) is the jQuery-selected version of that element. 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.

例如,如果要查找当前选定元素的父级的"sub-menu-wrap",则可以在函数内编写var subMenu = $(this).closest('.sub-menu-wrap'),然后从那里可以检查和修改样式和课程

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

jQuery将使您的生活更加轻松.您所遇到的每个问题也将在互联网上获得一百万个答案.

jQuery will make your life loads easier. Every question you have will have a million answers across the internet already as well.

这篇关于如何获得数组中每个项目的最后一个元素子项,然后在单击它们时显示它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆