點擊 <li> 時,需獲取上一次點擊的索引,而非當前索引。
var preIndex = -1; // 初始化為 -1 表示無上一次
$('li').on('click', function() {
console.log('上一次索引:', preIndex); // 輸出上一次
preIndex = $(this).index(); // 更新為當前
console.log('當前索引:', preIndex);
});
preIndex 保持狀態;