我有一个像这样的数组。
var myArray = ["1", "2", "3", "4", "5"];
当我点击下一个时,我需要找到下一个元素。假设我在变量中输入了2,当我点击" next"按钮,我需要检查数组并获得3等等。
答案 0 :(得分:3)
<强> jQuery的:强>
您应该使用.inArray()
和模数运算符:
var myArray = ["1", "2", "3", "4", "5"];
var val = "2";
var next = myArray[($.inArray(val, myArray) + 1) % myArray.length];
<强> DEMO 强>
<强> JavaScript的:强>
var myArray = ["1", "2", "3", "4", "5"];
var val = "2";
var index = myArray.indexOf(val);
if(index >= 0 && index < myArray.length - 1){
var next = myArray[index + 1];
alert(next);
}
<强> DEMO 强>
答案 1 :(得分:0)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="next" id="next">
<script>
var globle = 0; // by default first page
var myArray = ["1", "2", "3", "4", "5"];
$(document).ready(function(){
$("#next").click(function(){
if(globle == myArray.length){
globle = 0;
}
alert(myArray[globle]);
globle++;
});
});
</script>
答案 2 :(得分:0)
试试这个:
var myArray = ["1", "2", "3", "4", "5"];
var val = "2";
function checknext() {
var next = $.inArray(val, myArray) + 1;
if (next < myArray.length) {
val = myArray[next];
alert(val);
}
else {
alert("No More Item Exist");
}
}
function checkprv() {
var prv = $.inArray(val, myArray) - 1;
if (prv >= 0) {
val = myArray[prv];
alert(val);
}
else {
alert("No More Item Exist");
}