如何使用事件处理程序连续循环遍历数组列表(从结束恢复到开始)
How can I continuously cycle through an array list (from the end reverting back to the start) using an event handler
下面的函数使用ctrl向左/向右箭头键循环浏览数组(summaryList);但是当它到达"item6"时,数组结束。我在设置到达数组中的最后一项后,下一次按键将从第一项(索引 0)开始的功能时遇到问题
var summaryList;
summaryList = [
'item0',
'item1',
'item2',
'item3',
'item4',
'item5',
'item6',
];
// Hold reference to the currently focused position
var currentPosition = 0;
// Maximum position we can navigate to is the last item in the summary list
var maxFocusablePosition = summaryList.length - 1;
// Utility function to focus a given position value
function focusPosition(position) {
console.log("focus position is called");
$('#' + summaryList[position]).focus().css('border', 'yellow');
};
$(document).keydown(function (event) {
if (event.which === 37 && event.ctrlKey) {
currentPosition > 0 ? currentPosition-- : maxFocusablePosition;
console.log('left');
}
if (event.which === 39 && event.ctrlKey) {
currentPosition < maxFocusablePosition ? currentPosition++ : 0;
console.log('right');
}
focusPosition(currentPosition);
});
}
var summaryList;
summaryList = [
'item0',
'item1',
'item2',
'item3',
'item4',
'item5',
'item6',
];
// Hold reference to the currently focused position
var currentPosition = 0;
// Maximum position we can navigate to is the last item in the summary list
var maxFocusablePosition = summaryList.length - 1;
// Utility function to focus a given position value
function focusPosition(position) {
alert(position+" = "+summaryList[position]);
//$('#' + summaryList[position]).focus().css('border', 'yellow');
};
$(document).keydown(function (event) {
if (event.which==37) {
currentPosition = (currentPosition>0) ? parseInt(currentPosition)-1 : maxFocusablePosition;
//alert('left');
}
if (event.which==39) {
currentPosition = (currentPosition<maxFocusablePosition) ? parseInt(currentPosition)+1 : 0;
//alert(currentPosition);
//alert('right');
}
focusPosition(currentPosition);
});
为了满足您的要求,进行了某些修改,一切正常,这里只有一件事出错,那就是 currentPosition
var,它不是 int var,您尝试递增它,因此使用 parseInt
将currentPosition
转换为 int,您的代码工作正常。
注意:始终建议使用括号,同时使用较短的if和else语句EG。
(condition) ? statement : statement
小提琴 : https://jsfiddle.net/e54ax51j/1/
删除最后一个:
}
在关闭键关闭事件后发生。这会导致错误。
相关文章:
- 为什么“;未定义的“;在JavaScript中结束循环
- 为什么不是't窗口.恢复正常工作吗?(javascript/jquery)
- 循环结束/推送到数组之前在页面上呈现EJS
- 如何临时暂停浏览器渲染,然后恢复整个页面
- NodeJS-readline暂停和恢复事件发射器(逐行读取)
- 在另一个函数成功结束后调用该函数
- 谷歌地图劫持了iphone's滚动(触摸事件)-如何恢复
- 在动画结束之前调用函数
- 我希望在不替换现有变量的情况下恢复localStorage中的变量
- 希望日期开始结束于while循环中的一个房间id的一个数组
- 使用nunjucks时发生块结束错误
- 克隆和恢复”;工具化的“;元素
- HTML5获取弧的坐标's结束
- 内容结束时停止无限滚动
- 使用jQuery插入HTML页面的第一个项目缺少结束标记
- 如何暂停和恢复jquery间隔
- 如何在视频上显示海报图像使用Jquery结束
- 如何使用事件处理程序连续循环遍历数组列表(从结束恢复到开始)
- 如何从上次结束恢复计数器
- 在窗口大小调整事件开始时暂停 Greensock 动画,在调整大小事件结束时恢复动画