单击时保持导航元素突出显示

时间:2021-06-05 15:38:02

I have been trying to use the following code to get my nav element to stay highlighted once clicked. My page will not reload, but will display all content on one page - show this should work. Do I have a problem with selectors? Or is something else wrong? It looks like it should be working to me...

我一直在尝试使用以下代码使我的nav元素在单击后保持突出显示。我的页面不会重新加载,但会在一个页面上显示所有内容 - 显示这应该有效。我有选择器的问题吗?还是别的错了?它看起来应该对我有用......

HTML:

HTML:

<div class="admin-main-area">
   <div class="admin-left-nav">
      <ul id="admin-left-links">
         <li><a class="link" href="#">Orders</a></li>
         <li><a class="link" href="#">Reports</a></li>
         <li><a class="link" href="#">Add Product</a></li>
         <li><a class="link" href="#">Update Products</a></li>
         <li><a class="link" href="#">Update Stock</a></li>
         <li><a class="link" href="#">Update Pricing</a></li>
      </ul>
   </div>
   <div  class="admin-content-area">
      <p>this is some content</p>
   </div>
</div>

Javascript:

使用Javascript:

<script>
$('a.link').click(function(){
    $('a.link').removeClass("active");
    $(this).addClass("active");
});
</script>

CSS:

CSS:

.active {
    background-color: #f43333;
}

2 个解决方案

#1


1  

At the time you setup the click event handlers the links are not yet loaded in the DOM.

在设置click事件处理程序时,链接尚未加载到DOM中。

Try this (it will setup the handlers when the DOM is loaded):

试试这个(它会在加载DOM时设置处理程序):

$(window).ready(function() {
  $('a.link').click(function() {
    $('a.link').removeClass("active");
    $(this).addClass("active");
  });

})

Of course, you will also need to include jQuery before the <script> snippet

当然,您还需要在

Here's a working fiddle: https://jsfiddle.net/nsjfe5g1/

这是一个工作小提琴:https://jsfiddle.net/nsjfe5g1/

#2


1  

I don't understand what you need , but for my understandings you can simply do this with css :focus selector

我不明白你需要什么,但是根据我的理解,你可以用css:focus selector来做到这一点

a:focus {
  background-color: #f43333;
}

Try with demo https://jsfiddle.net/nsjfe5g1/2/

尝试使用demo https://jsfiddle.net/nsjfe5g1/2/

#1


1  

At the time you setup the click event handlers the links are not yet loaded in the DOM.

在设置click事件处理程序时,链接尚未加载到DOM中。

Try this (it will setup the handlers when the DOM is loaded):

试试这个(它会在加载DOM时设置处理程序):

$(window).ready(function() {
  $('a.link').click(function() {
    $('a.link').removeClass("active");
    $(this).addClass("active");
  });

})

Of course, you will also need to include jQuery before the <script> snippet

当然,您还需要在

Here's a working fiddle: https://jsfiddle.net/nsjfe5g1/

这是一个工作小提琴:https://jsfiddle.net/nsjfe5g1/

#2


1  

I don't understand what you need , but for my understandings you can simply do this with css :focus selector

我不明白你需要什么,但是根据我的理解,你可以用css:focus selector来做到这一点

a:focus {
  background-color: #f43333;
}

Try with demo https://jsfiddle.net/nsjfe5g1/2/

尝试使用demo https://jsfiddle.net/nsjfe5g1/2/