简体   繁体   English

在单击事件上,从不同级别向每个 HTML 元素添加 Class,

[英]On click event add Class to each HTML Element from different levels,

I'm new in programming so I'm trying to figure out the following situation for my college app.我是编程新手,所以我想弄清楚我的大学应用程序的以下情况。 I basically would like to loop through the whole Navigation menu and add an another Class where my CSS style would by applied.我基本上想遍历整个导航菜单并添加另一个类来应用我的 CSS 样式。 PS: It has to include the Submenus! PS:它必须包括子菜单!

Here's what a got so far using JQuery but I think that there is a better way to do it using vanilla Javascript.这是到目前为止使用 JQuery 的方法,但我认为使用 vanilla Javascript 有更好的方法来做到这一点。

$(document).ready(function () {
var speed = 200;
$(".sidebar-menu > li.have-children > a").click(function(e){
  e.preventDefault();
  if ( ! $(this).parent().hasClass("active") ){
    $(".sidebar-menu li ul").slideUp(speed);
    $(this).next().slideToggle(speed);
    $(".sidebar-menu li").removeClass("active");
    $(this).parent().addClass("active");
  } else {
    $(this).next().slideToggle(speed);
    $(".sidebar-menu li").removeClass("active");
  }
}); });

// ADD CLASS="SELECTED" TO "A" HTML ELEMENT IN "parent-menu" LINK
$(document).ready(function() {
$(".parent-menu").click(function () {
  $(this).addClass("selected");
  $(".parent-menu").not(this).removeClass("selected");
}); });

// ADD CLASS="SELECTED" TO "A" HTML ELEMENT IN "children-menu" LINK
$(document).ready(function() {
$(".children-menu").click(function () {
  $(this).addClass("selected");
  $(".children-menu").not(this).removeClass("selected");
}); });

Here an example: https://jsfiddle.net/clovisrosa/gw3myLfs/1/这里有一个例子: https : //jsfiddle.net/clovisrosa/gw3myLfs/1/

The original idea for the menu came from "VSCode Docs" website.菜单的最初想法来自“VSCode Docs”网站。 https://code.visualstudio.com/docs https://code.visualstudio.com/docs

As you can see, a different style is applied when you click.如您所见,单击时应用了不同的样式。 but I would like to load the page with the button "Home" already selected and move it as it is clicked.但我想加载已选择“主页”按钮的页面,并在单击时移动它。 Also, the code seems to be a bit kludging LOL!!此外,代码似乎有点笨拙,哈哈!!

You have many options.你有很多选择。 Here's two of them.这是其中的两个。

1) Add it to the HTML manually: 1) 手动将其添加到 HTML 中:

<li id="home" class="parent-menu selected"><a href="#home">HOME</a></li>

2) Use jQuery to simulate a click: 2)使用jQuery模拟点击:

$("#home").click();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM