开发者

Jquery change css class when achor clicked

开发者 https://www.devze.com 2023-03-28 10:10 出处:网络
I am trying to add a class to a list item when the item is clicked. I did some research and still was unable to ad开发者_如何学Pythond the class properly. thanks!

I am trying to add a class to a list item when the item is clicked. I did some research and still was unable to ad开发者_如何学Pythond the class properly. thanks!

edit:I am using a masterpage in asp.net

<ul id="menu">
      <!-- put class="selected" in the li tag for the selected page - to highlight which page you're on -->
      <li><a id="default" href="Default.aspx">Home</a></li>
       <li><a id="projects" href="Projects.aspx">Projects</a></li>
      <li><a id="blogs" href="Blogs.aspx">Blogs</a></li>
      <li><a id="photos" href="Photos.aspx">Photos</a></li>
       <li><a id="resume" href="Resume.aspx">Resume</a></li>
      <li><a id="contacts" href="Contact.aspx">Contact</a></li>
    </ul>

<script type="text/javascript" language="javascript">
   $(document).ready(function () {
       $('ul.menu li a').click(function () {
           $(this).parent().addClass('selected');
       });
   });

ul#menu li a:hover, ul#menu li.selected a, ul#menu li.selected a:hover

{ color: #FFF; background: #1C2C3E url(menu_select.png) repeat-x;}


your selector is incorrect. ul.menu means a ul with class menu.
when looking for an id, simply use $("#menu")

also, you may want to take a look at the answers given by @DefyGravity and @Joseph Silber-
they suggest that if you don't prevent the default click event, the user's browser would simply follow the link, and the user would never actually see the added class, since they'll be navigated to a different page.


Change your jQuery to this:

$(document).ready(function () {
    $('ul#menu li a').click(function (e) {
        $(this).parent().addClass('selected');
        e.preventDefault();
    });
});

You had the ul.menu which is referring to a class of menu, where as you have an ID of menu on the tag


You have to return false, otherwise the browser just follows the link:

 $(document).ready(function () {
       $('ul#menu li a').click(function () {
           $(this).parent().addClass('selected');
           return false;
       });
 });


you have a typo in your selector, ul.menu looks for a unordered list with a 'class' of menu. your html states it the un-ordered list has an ID of menu. You may also want to 'event.preventDefault()':

    <script type="text/javascript" language="javascript">
           $(document).ready(function () {
               $('#menu li a').click(function (event) {
     event.preventDefault();
                   $(this).parent().addClass('selected');
// also think about removing the class 'selected' from all the other links.
  $(this).parent().siblings('.selected').removeClass('selected');
               });
           });
        </script>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号