简体   繁体   中英

Dynamic jQuery Progress Bar - Click Events Not Working

I have a working JSFiddle where I'd like to be able to change how "filled" the progress bar is depending on the button clicked . When I click said buttons, nothing is happening.

I (previously) added in alerts/logs to make sure that I had the click functionality correct and due to those alerts/logs working once a button was clicked, I'm lead to believe that I just have something wrong in the way I am trying to move the progress bar.

$('.quarter').click(function(){
  $(this).parent().prev().children('span').css('width','25%');
  });
$('.half').click(function(){
  $(this).parent().prev().children('span').css('width','50%');
  });
$('.three-quarters').click(function(){
  $(this).parent().prev().children('span').css('width','75%');
  });
$('.full').click(function(){
  $(this).parent().prev().children('span').css('width','100%');
  });  

Change

  $(this).parent().prev().children('span')

to

$('.progress-bar > span')

With jquery, using these .parent().prev().etc chains will never end well. It's too easy to break by making small changes to your DOM.

fiddle

$(this) is probably not returning what you think it is. Consider that $(this) relates to the container that the code itself is in; ponder on that for a while and make a comment if you need me to elaborate.

David784 has a great solution for your code as is. Alternatively, consider giving the span that is the moving part of your progress bar some identifier. As an example, while the following will work for changing your progress bar to 100%,

$('span').css('width', '100%');

you'll be changing every span in your code if you have them.

Your paragraph holding the links was closed, but not opened:

    <p> <!-- Here -->
        <a href="#" class="quarter">25%</a>
        <a href="#" class="half">50%</a>
        <a href="#" class="three-quarters">75%</a>
        <a href="#" class="full">100%</a>
    </p>

Fixed JSFiddle: https://jsfiddle.net/j6jxpLwx/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM