为什么在将变量乘以2并将值赋给另一个变量时,我得到0?基本上,每次按下按钮时,我都会尝试逐步显示/隐藏块。但是,当我算上++ * 2时它会起作用。
请参阅以下代码以供参考。
var count = 0,
num = count * 2;
$('.load').on('click', function() {
$('.blocks').show();
$('.blocks').slice(num).hide();
count++;
});
console.log(num); // num is = to 0

.load {
display: block;
margin: 40px 0 0 0;
}
.blocks {
width: 30px;
height: 30px;
background: #000;
display: inline-block;
margin: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="load">Load this</button>
<div class="blocks"></div>
<div class="blocks"></div>
<div class="blocks"></div>
<div class="blocks"></div>
<div class="blocks"></div>
<div class="blocks"></div>
<div class="blocks"></div>
<div class="blocks"></div>
<div class="blocks"></div>
<div class="blocks"></div>
&#13;
答案 0 :(得分:2)
// initial variable initialization
var count = 0,
num = count * 2;
$('.load').on('click', function() {
$('.blocks').show();
$('.blocks').slice(num).hide();
// increment the count value
count++;
// re assign a new num value
num = count * 2;
console.log(num);
// num is 0,2,4,6
});
console.log(num); // num is = to 0
答案 1 :(得分:0)
使num成为一个简单的函数:
function num() { return count * 2; }