Why can't jquery.animate () use $ (this)?

I have a progress bar with bootstrap, this is html:

$(".progress-bar").animate({
  width: $(this).data('width') + '%'
}, 2500);
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="alert alert-success">
  <div class="skill-name">ON PROGRESS 357/487</div>
  <div class="progress">
    <div class="progress-bar progress-bar-primary" role="progressbar" data-width="70">
    </div>
  </div>
</div>
Run code

why jquery above doesn't work if i used $(this).data('width') + '%'. But if I used $(".progress-bar").data('width') + '%', worked.? thank

Edit

If I use $(".progress-bar").data('width') + '%', it will change everything .progress-bar.

+4
source share
1 answer

You are dealing with the problem of defining an area. The method .animate()covers only thisinside its callback complete. Otherwise, he will probably identify him to the caller.

, . , , , this jQuery.

var progressBar = $(".progress-bar");
progressBar.animate({
  width: progressBar.data('width') + '%'
}, 2500);

, .each(), .

$(".progress-bar").each(function(i, item) {
  var progressBar = $(item); // $(this) would work too
  progressBar.animate({
    width: progressBar.data('width') + '%'
  }, 2500);
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="alert alert-success">
  <div class="skill-name">ON PROGRESS 357/487</div>
  <div class="progress">
    <div class="progress-bar progress-bar-primary" role="progressbar" data-width="70">
    </div>
  </div>
</div>
+6

Source: https://habr.com/ru/post/1669010/


All Articles