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

waw*_*wan 4 html css jquery twitter-bootstrap

我有引导程序的进度条,这是html:

$(".progress-bar").animate({
  width: $(this).data('width') + '%'
}, 2500);
Run Code Online (Sandbox Code Playgroud)
<!-- 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 Online (Sandbox Code Playgroud)

为什么如果我使用jquery上面不工作$(this).data('width') + '%'.但如果我用过$(".progress-bar").data('width') + '%'工作.?谢谢

编辑

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

Sov*_*iut 6

你正在处理一个范围问题.该.animate()方法仅this在其complete回调范围内.否则,它可能会将其范围限定给调用者.

要解决此问题,请将您的选择缓存在变量中,并在其余代码中使用它.除了始终保持正确的范围外,这在技术上更快,因为它不需要重新包装this在jQuery对象中.

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

如果您正在处理多个进度条,则可以使用.each()它们迭代它们并将动画应用于每个元素,同时它们仍在范围内.

$(".progress-bar").each(function(i, item) {
  var progressBar = $(item); // $(this) would work too
  progressBar.animate({
    width: progressBar.data('width') + '%'
  }, 2500);
});
Run Code Online (Sandbox Code Playgroud)
<!-- 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 Online (Sandbox Code Playgroud)