jQuery Adding a css class to a link when clicked

雨燕双飞 提交于 2019-12-23 01:57:16

问题


I have the current code:

<script type="text/javascript">
$('ul.products-slideshow-thumbs li a').bind("mousedown", function(){
  $(this).toggleClass("current");
});
</script>

<ul class="products-slideshow-thumbs">
  <li><a href="#"><img src="product-slides/thumbs/1.jpg" /></a></li>
  <li><a href="#"><img src="product-slides/thumbs/2.jpg" /></a></li>
  <li><a href="#"><img src="product-slides/thumbs/3.jpg" /></a></li>
</ul>

But it's not working properly (basically, nothing happens).
Any suggestions? (I'm afraid I'm fairly new to jQuery/JavaScript.) Thank you!


回答1:


Try this:

<script type="text/javascript">
 $(document).ready(function(){   
   $('ul.products-slideshow-thumbs li a').click(function(){
      $(this).toggleClass("current");
    });
  });
</script>

<ul class="products-slideshow-thumbs">
  <li><a href="#"><img src="product-slides/thumbs/1.jpg" /></a></li>
  <li><a href="#"><img src="product-slides/thumbs/2.jpg" /></a></li>
  <li><a href="#"><img src="product-slides/thumbs/3.jpg" /></a></li>
</ul>



回答2:


I copied your code and it seemed to work for me. Have you also tried the .click() jquery method?

http://jsfiddle.net/jordanlewis/X6mn5/



来源:https://stackoverflow.com/questions/5545553/jquery-adding-a-css-class-to-a-link-when-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!