我可以将“this”作为参数传递给javascript中的另一个函数

我有这个:

$('#slider li').click(function () { var stepClicked = $(this).index(); alert(stepClicked); if (stepClicked != 0) { $('#cs_previous').removeClass('cs_hideMe'); } else { $('#cs_previous').addClass('cs_hideMe'); } $('li.cs_current').removeClass('cs_current'); $($(this)).addClass('cs_current'); moveToNextImage(stepClicked); function moveToNextImage(stepClicked) { alert(stepClicked); var currentIs = $('li.cs_current').index(); var newLeftEdge = currentIs - stepClicked; $('.cs_riskStageImage').fadeTo(200, .2).animate({ left: newLeftEdge }, "fast").fadeTo(200, 1); }; }); 

警报显示所点击的li的正确索引,当我在我正在调用的最后一个函数moveToNextImage(stepClicked)警告变量时,相同的值显示但动画没有发生。 这有很多其他方法,但我试图传递单击列表项的索引值以用于计算数学。

..或者我可以将值转换为第一个函数中的另一个变量,我可以传递给第二个吗?

javascript函数call()apply()都是为了在上下文中调用函数。

 function sum() { return this.num1 + this.num2; } function callSum(num1, num2) { this.num1 = num1 this.num2 = num2 return sum.call(this); //call sum() in the context of this } alert(callSum(10, 15)); function applySum(num1, num2) { this.num1 = num1 this.num2 = num2 return sum.apply(this); //call sum() in the context of this } alert(applySum(30, 45)); 

jsfiddle示例链接

现在在sum()函数中, this关键字与callSum()applySum()函数具有相同的上下文。

call()apply()之间的区别在于apply的第二个参数是要传递的arguments数组或arguments对象。

你可以将它传递给另一个函数

 moveToNextImage(this, stepClicked); function moveToNextImage(obj, stepClicked) { var index = $(obj).index; } 

在你的代码中,这一行意味着什么

 $($(this)).addClass('cs_current'); 

应该是这样的

 $(this).addClass('cs_current');