javascript 使用javascript将活动类添加到主菜单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31087198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:15:39  来源:igfitidea点击:

add active class to main menu using javascript

javascripthtmlcssmenuitem

提问by Tufan Chand

I have searched a lot for adding active class to the parent menu using javascript.

我已经搜索了很多使用javascript.

I found many more examples but not a single one is working for me, below is my code

我发现了更多的例子,但没有一个对我有用,下面是我的代码

HTML

HTML

<div id="menu1" class="hmenu">
    <ul>
        <li><a href="#">Item1</a>
            <ul>
                <li><a href="#">SubItem1</a>
                    <ul>
                        <li><a href="#">SubSubItem1</a></li>
                        <li><a href="#">SubSubItem2</a></li>
                    </ul>
                </li>
                <li><a href="#">SubItem2</a> </li>
                <li><a href="#">SubItem3</a>
                    <ul>
                        <li><a href="#">SubSubItem1</a></li>
                        <li><a href="#">SubSubItem2</a></li>
                    </ul>
                </li>
            </ul>
        </li>
        <li><a href="#">Item2</a></li>
        <li><a href="#">Item3</a>
            <ul>
                <li><a href="#">SubItem1</a>
                    <ul>
                        <li><a href="#">SubSubItem1</a></li>
                        <li><a href="#">SubSubItem2</a></li>
                    </ul>
                </li>
            </ul>
        </li>
    </ul>
    <br style="clear: left" />
</div>

My requirement is when i click on SubItem1then both Item1and SubItem1should be active.

我的要求是当我单击SubItem1 时Item1SubItem1都应该处于活动状态。

And when i click on SubSubItem1then SubSubItem1,SubItem1and Item1should be active.

当我点击SubSubItem1然后SubSubItem1SubItem1Item1应该是活动的。

Means when click on any link then its all parent link and the same link should be active.

意味着当点击任何链接时,它的所有父链接和相同的链接都应该是活动的。

I have tried with this javascriptcode :

我试过这个javascript代码:

$(document).ready(function () {
        $('.hmenu ul li ul').find('li').click(function () {
            //removing the previous selected menu state
            $('.hmenu').find('li.active').removeClass('active');
            //adding the state for this parent menu
            $(this).parents('li').addClass('active');
        });
    });

Actually i don't have any experience with javascriptcoding and unable to figure out the problem in my code.

实际上,我没有任何javascript编码经验,也无法找出我的code.

Can anyone suggest me for the same.

任何人都可以建议我这样做。

回答by Delgan

The issue comes from .find('li').click().

问题来自.find('li').click().

As you use nestsed <li>, this will cause the event to be fired two times when you click on a child <li>. This causes problems. Can not you add the click()to <a>elements?

当您使用嵌套时<li>,这将导致当您单击子项时两次触发该事件<li>。这会导致问题。你不能添加click()to<a>元素吗?

$(document).ready(function () {
    $('.hmenu a').click(function () {
        //removing the previous selected menu state
        $('.hmenu').find('li.active').removeClass('active');
        //adding the state for this parent menu
        $(this).parents("li").addClass('active');

    });
});

It works just fine: https://jsfiddle.net/6put8tdx/

它工作得很好:https: //jsfiddle.net/6put8tdx/



Note that your page will be bumped to the top while clicking to atab because of #anchor. If you want to prevent this, you may pass the event to the function .click(function (event) {...}and add event.preventDefaultinside.

请注意,a由于#锚点,您的页面在单击选项卡时会被撞到顶部。如果你想防止这种情况,你可以将事件传递给函数.click(function (event) {...}并在event.preventDefault里面添加。

回答by Roko C. Buljan

If you need the click target to be the LI element (as opposed to Delgan's answer)

如果您需要将点击目标作为 LI 元素(与 Delgan 的答案相反)

you can use .not()over the targeted LI's parentsto prevent messing with the bubbling event targets:

您可以使用.not()目标 LIparents来防止与冒泡事件目标混淆:

$(document).ready(function () {

  $('.hmenu').find('li').click(function(event) {
    event.preventDefault();                   // Prevent page jumps due to anchors
    var $par = $(event.target).parents("li"); // get list of parents
    $(".hmenu .active").not( $par ).removeClass("active");  // not them
    $(this).addClass('active');               // let the event propagation do the work
  });

});

$(document).ready(function () {

  $('.hmenu').find('li').click(function(event) {
    event.preventDefault(); 
    var $par = $(event.target).parents("li");
    $(".hmenu .active").not($par).removeClass("active");
    $(this).addClass('active');
  });

});
.active > a{
  background: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <div id="menu1" class="hmenu">
      <ul>
        <li><a href="#">Item1</a>
          <ul>
            <li><a href="#">SubItem1</a>
              <ul>
                <li><a href="#">SubSubItem1</a></li>
                <li><a href="#">SubSubItem2</a></li>
              </ul>
            </li>
            <li><a href="#">SubItem2</a> </li>
            <li><a href="#">SubItem3</a>
              <ul>
                <li><a href="#">SubSubItem1</a></li>
                <li><a href="#">SubSubItem2</a></li>
              </ul>
            </li>
          </ul>
        </li>
        <li><a href="#">Item2</a></li>
        <li><a href="#">Item3</a>
          <ul>
            <li><a href="#">SubItem1</a>
              <ul>
                <li><a href="#">SubSubItem1</a></li>
                <li><a href="#">SubSubItem2</a></li>
              </ul>
            </li>
          </ul>
        </li>
      </ul>
      <br style="clear: left" />
    </div>

To better understand the above
The following example works out-of-the-box, and the clicked one and all it's LI parents get the "active"class.
Why?Cause the event target is li, means any liof .hmenu- so that click is attachedto any of them, and clicking the subsubLI the event will propagate to the LIparents - triggering the same clickbehavior (this add class)!

为了更好地理解上面
的内容,下面的示例开箱即用,点击一个和所有它的 LI 父母都得到了"active"类。
为什么?因为事件目标是li, 意味着任何li一个.hmenu- 以便单击附加到它们中的任何一个,并且单击subsubLI 事件将传播到LI父级 - 触发相同的click行为(这个添加类)!

$(".hmenu").on("click", "li", function(){
   $(this).addClass("active"); // Wow! Event propagation rulez!!
});

But we need to remove existing .activeand here it gets messy...

但是我们需要删除现有的.active,在这里它变得凌乱......

$(".hmenu").on("click", "li", function(){
   $(".active").removeClass("active"); // triggered on every event bubble :(
   $(this).addClass("active"); // leaving only the main parent with active class
});

That's caused by the concurrency that happens while the event bubbles and triggers the same actions for the parent elements.

这是由事件冒泡并触发父元素的相同操作时发生的并发引起的。

One way to prevent that concurrency would be using a setTimeoutof 1ms:

防止这种并发的一种方法是使用 a setTimeoutof 1ms:

$(".hmenu").on("click", "li", function(){
   $(".active").removeClass("active");
   setTimeout(function(){  // Let the previous finish the bubbling mess
      $(this).addClass("active"); // Yey! all fine! Every LI has the active class
   }, 1);
});

But here the timeout of 1mscan lead to visual "blinking" issues.

但在这里超时1ms可能导致视觉“闪烁”问题。

回答by brroshan

Try this:

试试这个:

 $(function () {
     $("li a")
       .on("click", function () {
         $(this).toggleClass("active");
         $(this).closest("ul").parent().children("li a").toggleClass("active")
       .parent().parent().parent().children("li a").toggleClass("active");

     });
 });

fiddle

小提琴

Traverse from the clicked element. And use toggleClass()to avoid the mundane checking if hasclassremoveClass...

从单击的元素开始遍历。并用于toggleClass()避免平凡的检查,如果hasclassremoveClass...