jQuery Adding a css class to a link when clicked

2019-06-08 06:12发布

问题:

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/