jQuery Adding a css class to a link when clicked

2019-06-08 05:52发布

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!

2条回答
叛逆
2楼-- · 2019-06-08 06:02

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

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

查看更多
小情绪 Triste *
3楼-- · 2019-06-08 06:08

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>
查看更多
登录 后发表回答