使用jQuery浏览函数数组
Navigate an array of functions using jQuery
我正试图通过jQuery的"向前"answers"向后"按钮在函数数组中正确"导航"。我的后退按钮出现问题,导航不正确。
var functions = [ function0, function1, function2, function3, function4, function5 ];
var index = 0;
$("#forward").click(function() {
functions[Math.abs(index % functions.length)]();
index++;
});
$("#back").click(function() {
functions[Math.abs(index % functions.length)]();
index--;
});
这是完整的代码:
https://jsfiddle.net/sa13yrtf/2/
您应该按正确的顺序更改索引。
$("#forward").click(function(){
if(index < functions.length){
index++;
functions[Math.abs(index % functions.length)]();
}
});
$("#back").click(function(){
if(index > 1){
index--;
functions[Math.abs(index % functions.length)]();
}
});
检查更新的fiddle
$("#forward").click(function(){
index = index == functions.length - 1 ? 0: index + 1; //number incremented before calling the function and in incremental fashion
functions[Math.abs(index % functions.length)]();
});
$("#back").click(function(){
index = index ? index - 1 : functions.length-1 ; //number decremented before calling the function and in incremental fashion
functions[Math.abs(index % functions.length)]();
});
这里是一种面向对象的方法。Navigator
类为您跟踪索引。
function Navigator(fnArr, fwdSelector, bakSelector) {
this.fnArr = fnArr || [];
this.index = 0;
$(fwdSelector).click($.proxy(this.forward, this));
$(bakSelector).click($.proxy(this.reverse, this));
}
Navigator.prototype = {
rotate : function(direction) {
this.executeFn(Math.abs((this.index += direction) % this.fnArr.length));
},
forward : function() {
if (this.index < this.fnArr.length - 1) { this.rotate(+1); }
},
reverse : function() {
if (this.index > 0) { this.rotate(-1); }
},
executeFn : function(index) {
this.fnArr[index || 0]();
}
};
var fnArr = [
function function0() { $('p').text('0'); },
function function1() { $('p').text('1'); },
function function2() { $('p').text('2'); },
function function3() { $('p').text('3'); },
function function4() { $('p').text('4'); },
function function5() { $('p').text('5'); }
];
var nav = new Navigator(fnArr, '#forward', '#back');
nav.executeFn();
.pure-button-primary { font-weight: bold; }
p { width: 2.8em; text-align: center; font-weight: bold; font-size: 2em; margin: 0.25em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/pure/0.6.0/buttons-min.css" rel="stylesheet"/>
<div class="pure-button pure-button-primary" id="back"><<</div>
<div class="pure-button pure-button-primary" id="forward">>></div>
<p></p>
相关文章:
- 数组函数不适用于从元素文本创建的JavaScript数组
- 如何在javascript中求解pack数组函数
- 制作一个javascript的数组函数
- 获取元素的位置并创建它的数组函数
- 茉莉花中的 SpyOn javascript 数组函数
- 自定义数组函数不接受参数
- 使用原型的自定义数组函数.新的 MyArray(1,2,3,4) 不工作
- Java 脚本随机化数组函数
- 在 Restangular 集合上使用 lodash 数组函数
- 比较数组函数返回未定义
- Javascript中嵌套for循环与数组函数的性能
- 多维数组函数在JS中不起作用
- Javascript数组函数有我看不到的错误
- 数组函数外的javascript
- 在数组/函数中循环时使用换行符
- 拼接javascript数组函数获胜't删除项目
- 为什么不'这个js数组函数不能工作
- 如何在我自己的数组原型函数中使用数组函数
- 在javascript中定义数组函数
- Jquery动态树数组函数