为什么 $(this) 不能在 jquery .animate() 中使用?



我有带有引导程序的进度条,这是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>

如果我使用$(this).data('width') + '%',为什么上面的jQuery不起作用。但是如果我使用$(".progress-bar").data('width') + '%'工作。?谢谢

编辑

如果我使用$(".progress-bar").data('width') + '%'它将改变所有.progress-bar.

您正在处理范围问题。.animate()方法仅在其complete回调内限定this范围。否则,它可能会将其范围限定为调用方。

若要解决此问题,请将所选内容缓存在变量中,并在代码的其余部分中使用它。除了始终保持正确的作用域外,这在技术上也更快,因为它不需要在 jQuery 对象中重新包装this

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>

最新更新