我有两个不同函数的变量index_1
和index_2
,我必须对其进行比较。这是正确的方法还是我可以采取其他方法
目前,我对这个用于比较的代码不满意,因为每次我都得到相同的值:
$(document).ready(function(){
var index_1 = '';
var index_2 = '';
$('#spin-now').click(function(){
$(".spin-box-1").jCarouselLite({
auto: 200,
speed: 200,
visible: 1,
vertical: true,
easing: "easeOutBounce",
afterEnd: function(a) {
var index_1 = $(a[0]).index();
store_index_1(index_1);
}
});
$(".spin-box-2").jCarouselLite({
auto: 225,
speed: 225,
visible: 1,
vertical: true,
easing: "easeOutBounce",
afterEnd: function(a) {
var index_2 = $(a[0]).index();
store_index_1(index_2);
}
});
});
function store_index_1(x){
data_index_1 = x;
data_index_2 = data_index_1 ;
if(data_index_2 == data_index_1){
//alert('same');
}
else{
alert('different');
}
console.log('outside'+''+data_index_1+''+data_index_2);
}
//console.log(data_index_1);
});
最佳答案
(我认为这应该是一条评论,但我没有足够的声誉)
您定义了 2 个全局变量,因此如果您要使用它们,请将 .spin-box-1
的第一个索引保存在 index_1 和 .spin-box-2
在 index_2 中,然后调用“compare”函数(您的 store_index_1
)。
$(document).ready(function(){
var index_1 = '';
var index_2 = '';
$('#spin-now').click(function(){
$(".spin-box-1").jCarouselLite({
auto: 200,
speed: 200,
visible: 1,
vertical: true,
easing: "easeOutBounce",
afterEnd: function(a) {
index_1 = $(a[0]).index(); //index_1 is your global
}
});
$(".spin-box-2").jCarouselLite({
auto: 225,
speed: 225,
visible: 1,
vertical: true,
easing: "easeOutBounce",
afterEnd: function(a) {
index_2 = $(a[0]).index(); //index_2 is your global
}
});
compare(); //index_1 and index2 should be set by this line.
});
function compare(){
if(index_1 == index_2){
alert('same');
}
else{
alert('different');
}
console.log('outside'+''+index_1+''+index_2);
}
//rest of your code
});
您的 store_index_1(x)
函数的特点是它始终为 true,因为您正在比较 2 个相等的值:
data_index_2 = data_index_1 ;
if(data_index_2 == data_index_1)
这有点无稽之谈,所以我对你想做什么感到困惑。 再次对“答案”表示抱歉,因为我还无法发表评论。
关于javascript - 如何比较不同函数或同一函数的两个不同值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30544045/